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
GunoH/intellij-community
plugins/ide-features-trainer/src/training/ui/views/LearningItems.kt
4
7294
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package training.ui.views import com.intellij.ide.plugins.newui.VerticalLayout import com.intellij.openapi.project.DumbService import com.intellij.openapi.project.Project import com.intellij.ui.JBColor import com.intellij.ui.components.JBLabel import com.intellij.util.IconUtil import com.intellij.util.ui.EmptyIcon import com.intellij.util.ui.JBUI import com.intellij.util.ui.UIUtil import training.FeaturesTrainerIcons import training.learn.CourseManager import training.learn.LearnBundle import training.learn.course.IftModule import training.learn.course.Lesson import training.learn.lesson.LessonManager import training.statistic.LessonStartingWay import training.ui.UISettings import training.util.* import java.awt.* import java.awt.event.MouseAdapter import java.awt.event.MouseEvent import javax.swing.* import javax.swing.border.EmptyBorder private val HOVER_COLOR: Color get() = JBColor.namedColor("Plugins.hoverBackground", JBColor(0xEDF6FE, 0x464A4D)) class LearningItems(private val project: Project) : JPanel() { var modules: Collection<IftModule> = emptyList() private val expanded: MutableSet<IftModule> = mutableSetOf() init { name = "learningItems" layout = VerticalLayout(0, UISettings.getInstance().let { it.panelWidth - (it.westInset + it.eastInset) }) isOpaque = false isFocusable = false } fun updateItems(showModule: IftModule? = null) { if (showModule != null) expanded.add(showModule) removeAll() for (module in modules) { if (module.lessons.isEmpty()) continue add(createModuleItem(module), VerticalLayout.FILL_HORIZONTAL) if (expanded.contains(module)) { for (lesson in module.lessons) { add(createLessonItem(lesson), VerticalLayout.FILL_HORIZONTAL) } } } revalidate() repaint() } private fun createLessonItem(lesson: Lesson): JPanel { val name = JLabel(lesson.name).also { it.foreground = JBUI.CurrentTheme.Link.Foreground.ENABLED } val clickAction: () -> Unit = l@{ val cantBeOpenedInDumb = DumbService.getInstance(project).isDumb && !lesson.properties.canStartInDumbMode if (cantBeOpenedInDumb && !LessonManager.instance.lessonShouldBeOpenedCompleted(lesson)) { val balloon = createBalloon(LearnBundle.message("indexing.message")) balloon.showInCenterOf(name) return@l } CourseManager.instance.openLesson(project, lesson, LessonStartingWay.LEARN_TAB) } val result = LearningItemPanel(clickAction) result.layout = BoxLayout(result, BoxLayout.X_AXIS) result.alignmentX = LEFT_ALIGNMENT result.border = EmptyBorder(JBUI.scale(7), JBUI.scale(7), JBUI.scale(6), JBUI.scale(7)) val checkmarkIconLabel = createLabelIcon(if (lesson.passed) FeaturesTrainerIcons.GreenCheckmark else EmptyIcon.ICON_16) result.add(createLabelIcon(EmptyIcon.ICON_16)) result.add(scaledRigid(UISettings.getInstance().expandAndModuleGap, 0)) result.add(checkmarkIconLabel) result.add(rigid(4, 0)) result.add(name) if (iftPluginIsUsing && lesson.isNewLesson()) { result.add(rigid(10, 0)) result.add(NewContentLabel()) } result.add(Box.createHorizontalGlue()) return result } private fun createModuleItem(module: IftModule): JPanel { val modulePanel = JPanel() modulePanel.isOpaque = false modulePanel.layout = BoxLayout(modulePanel, BoxLayout.Y_AXIS) modulePanel.alignmentY = TOP_ALIGNMENT modulePanel.background = Color(0, 0, 0, 0) val clickAction: () -> Unit = { if (expanded.contains(module)) { expanded.remove(module) } else { expanded.clear() expanded.add(module) } updateItems() } val result = LearningItemPanel(clickAction) result.background = UISettings.getInstance().backgroundColor result.layout = BoxLayout(result, BoxLayout.X_AXIS) result.border = EmptyBorder(JBUI.scale(8), JBUI.scale(7), JBUI.scale(10), JBUI.scale(7)) result.alignmentX = LEFT_ALIGNMENT val expandPanel = JPanel().also { it.layout = BoxLayout(it, BoxLayout.Y_AXIS) it.isOpaque = false it.background = Color(0, 0, 0, 0) it.alignmentY = TOP_ALIGNMENT it.add(rigid(0, 1)) val rawIcon = if (expanded.contains(module)) UIUtil.getTreeExpandedIcon() else UIUtil.getTreeCollapsedIcon() it.add(createLabelIcon(rawIcon)) } result.add(expandPanel) val name = JLabel(module.name) name.font = UISettings.getInstance().modulesFont if (!iftPluginIsUsing || expanded.contains(module) || !module.lessons.any { it.isNewLesson() }) { modulePanel.add(name) } else { val nameLine = JPanel() nameLine.isOpaque = false nameLine.layout = BoxLayout(nameLine, BoxLayout.X_AXIS) nameLine.alignmentX = LEFT_ALIGNMENT nameLine.add(name) nameLine.add(rigid(10, 0)) nameLine.add(NewContentLabel()) modulePanel.add(nameLine) } modulePanel.add(scaledRigid(0, UISettings.getInstance().progressModuleGap)) if (expanded.contains(module)) { modulePanel.add(JLabel("<html>${module.description}</html>").also { it.font = UISettings.getInstance().getFont(-1) it.foreground = UIUtil.getLabelForeground() }) } else { modulePanel.add(createModuleProgressLabel(module)) } result.add(scaledRigid(UISettings.getInstance().expandAndModuleGap, 0)) result.add(modulePanel) result.add(Box.createHorizontalGlue()) return result } private fun createLabelIcon(rawIcon: Icon): JLabel = JLabel(IconUtil.toSize(rawIcon, JBUI.scale(16), JBUI.scale(16))) private fun createModuleProgressLabel(module: IftModule): JBLabel { val progressStr = learningProgressString(module.lessons) val progressLabel = JBLabel(progressStr) progressLabel.name = "progressLabel" val hasNotPassedLesson = module.lessons.any { !it.passed } progressLabel.foreground = if (hasNotPassedLesson) UISettings.getInstance().moduleProgressColor else UISettings.getInstance().completedColor progressLabel.font = UISettings.getInstance().getFont(-1) progressLabel.alignmentX = LEFT_ALIGNMENT return progressLabel } } private class LearningItemPanel(clickAction: () -> Unit) : JPanel() { init { isOpaque = false cursor = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR) addMouseListener(object : MouseAdapter() { override fun mouseClicked(e: MouseEvent) { if (!visibleRect.contains(e.point)) return clickAction() } override fun mouseEntered(e: MouseEvent) { parent.repaint() } override fun mouseExited(e: MouseEvent) { parent.repaint() } }) } override fun paint(g: Graphics) { if (mousePosition != null) { val g2 = g.create() as Graphics2D g2.color = HOVER_COLOR g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON) g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_NORMALIZE) g2.fillRoundRect(0, 0, size.width, size.height, JBUI.scale(5), JBUI.scale(5)) } super.paint(g) } }
apache-2.0
223da8e3001e2d00cd0cc48c6eeacdff
34.931034
144
0.710036
4.1279
false
false
false
false
jk1/intellij-community
plugins/testng/src/com/theoryinpractice/testng/configuration/TestNGRunConfigurationImporter.kt
3
3269
// 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.theoryinpractice.testng.configuration import com.intellij.execution.configurations.ConfigurationFactory import com.intellij.execution.configurations.ConfigurationTypeUtil import com.intellij.execution.configurations.RunConfiguration import com.intellij.openapi.externalSystem.service.project.IdeModifiableModelsProvider import com.intellij.openapi.externalSystem.service.project.settings.RunConfigurationImporter import com.intellij.openapi.project.Project import com.intellij.util.ObjectUtils.consumeIfCast import com.theoryinpractice.testng.model.TestType import java.util.* class TestNGRunConfigurationImporter: RunConfigurationImporter { override fun process(project: Project, runConfiguration: RunConfiguration, cfg: MutableMap<String, Any>, modelsProvider: IdeModifiableModelsProvider) { if (runConfiguration !is TestNGConfiguration) { throw IllegalArgumentException("Unexpected type of run configuration: ${runConfiguration::class.java}") } val allowedTypes = listOf("package", "class", "method", "group", "suite", "pattern") val testKind = cfg.keys.firstOrNull { it in allowedTypes && cfg[it] != null } val data = runConfiguration.data if (testKind != null) { consumeIfCast(cfg[testKind], String::class.java) { testKindValue -> data.TEST_OBJECT = when (testKind) { "package" -> TestType.PACKAGE.type.also { data.PACKAGE_NAME = testKindValue } "class" -> TestType.CLASS.type.also { data.MAIN_CLASS_NAME = testKindValue } "method" -> TestType.METHOD.type.also { val className = testKindValue.substringBefore('#') val methodName = testKindValue.substringAfter('#') data.MAIN_CLASS_NAME = className data.METHOD_NAME = methodName } "group" -> TestType.GROUP.type.also { data.GROUP_NAME = testKindValue } "suite" -> TestType.SUITE.type.also { data.SUITE_NAME = testKindValue } "pattern" -> TestType.PATTERN.type.also { data.setPatterns(LinkedHashSet(testKindValue.split(delimiters = ','))) } else -> data.TEST_OBJECT } } } consumeIfCast(cfg["vmParameters"], String::class.java) { runConfiguration.vmParameters = it } consumeIfCast(cfg["workingDirectory"], String::class.java) { runConfiguration.workingDirectory = it } consumeIfCast(cfg["passParentEnvs"], Boolean::class.java) { runConfiguration.isPassParentEnvs = it } consumeIfCast(cfg["envs"], Map::class.java) { runConfiguration.envs = it as Map<String, String> } consumeIfCast(cfg["moduleName"], String::class.java) { val module = modelsProvider.modifiableModuleModel.findModuleByName(it) if (module != null) { runConfiguration.setModule(module) } } } override fun canImport(typeName: String): Boolean = "testng" == typeName override fun getConfigurationFactory(): ConfigurationFactory = ConfigurationTypeUtil .findConfigurationType<TestNGConfigurationType>(TestNGConfigurationType::class.java) .configurationFactories[0] }
apache-2.0
bd465964a76d1735bb1f2e96d8fc3346
47.80597
140
0.71398
4.610719
false
true
false
false
himikof/intellij-rust
src/main/kotlin/org/rust/lang/core/psi/ext/RsExternCrateItem.kt
1
1312
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.lang.core.psi.ext import com.intellij.lang.ASTNode import com.intellij.psi.PsiElement import com.intellij.psi.stubs.IStubElementType import org.rust.ide.icons.RsIcons import org.rust.lang.core.psi.RsExternCrateItem import org.rust.lang.core.psi.RustPsiImplUtil import org.rust.lang.core.resolve.ref.RsExternCrateReferenceImpl import org.rust.lang.core.resolve.ref.RsReference import org.rust.lang.core.stubs.RsExternCrateItemStub abstract class RsExternCrateItemImplMixin : RsStubbedNamedElementImpl<RsExternCrateItemStub>, RsExternCrateItem { constructor(node: ASTNode) : super(node) constructor(stub: RsExternCrateItemStub, elementType: IStubElementType<*, *>) : super(stub, elementType) override fun getReference(): RsReference = RsExternCrateReferenceImpl(this) override val referenceNameElement: PsiElement get() = identifier override val referenceName: String get() = name!! override val isPublic: Boolean get() = RustPsiImplUtil.isPublic(this, stub) override fun getIcon(flags: Int) = RsIcons.CRATE } val RsExternCrateItem.hasMacroUse: Boolean get() = queryAttributes.hasAttribute("macro_use")
mit
806fc80bd357f0e141d85f2da078e88d
34.459459
108
0.762195
4.493151
false
false
false
false
jk1/intellij-community
java/idea-ui/src/com/intellij/codeInsight/daemon/impl/LibrarySourceNotificationProvider.kt
2
5052
// 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.codeInsight.daemon.impl import com.intellij.ProjectTopics import com.intellij.diff.DiffContentFactory import com.intellij.diff.DiffManager import com.intellij.diff.requests.SimpleDiffRequest import com.intellij.ide.util.PsiNavigationSupport import com.intellij.openapi.fileEditor.FileEditor import com.intellij.openapi.fileTypes.LanguageFileType import com.intellij.openapi.project.Project import com.intellij.openapi.project.ProjectBundle import com.intellij.openapi.roots.ModuleRootEvent import com.intellij.openapi.roots.ModuleRootListener import com.intellij.openapi.roots.ProjectRootManager import com.intellij.openapi.util.Key import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.* import com.intellij.psi.impl.source.PsiExtensibleClass import com.intellij.psi.util.PsiFormatUtil import com.intellij.psi.util.PsiFormatUtilBase import com.intellij.ui.EditorNotificationPanel import com.intellij.ui.EditorNotifications import com.intellij.ui.LightColors class LibrarySourceNotificationProvider(private val project: Project, notifications: EditorNotifications) : EditorNotifications.Provider<EditorNotificationPanel>() { private companion object { private val KEY = Key.create<EditorNotificationPanel>("library.source.mismatch.panel") private val ANDROID_SDK_PATTERN = ".*/platforms/android-\\d+/android.jar!/.*".toRegex() private const val FIELD = PsiFormatUtil.SHOW_NAME or PsiFormatUtil.SHOW_TYPE or PsiFormatUtil.SHOW_FQ_CLASS_NAMES private const val METHOD = PsiFormatUtil.SHOW_NAME or PsiFormatUtilBase.SHOW_PARAMETERS private const val PARAMETER = PsiFormatUtilBase.SHOW_TYPE or PsiFormatUtil.SHOW_FQ_CLASS_NAMES private const val CLASS = PsiFormatUtil.SHOW_NAME or PsiFormatUtil.SHOW_FQ_CLASS_NAMES or PsiFormatUtil.SHOW_EXTENDS_IMPLEMENTS } init { project.messageBus.connect(project).subscribe(ProjectTopics.PROJECT_ROOTS, object : ModuleRootListener { override fun rootsChanged(event: ModuleRootEvent) = notifications.updateAllNotifications() }) } override fun getKey(): Key<EditorNotificationPanel> = KEY override fun createNotificationPanel(file: VirtualFile, fileEditor: FileEditor): EditorNotificationPanel? { if (file.fileType is LanguageFileType && ProjectRootManager.getInstance(project).fileIndex.isInLibrarySource(file)) { val psiFile = PsiManager.getInstance(project).findFile(file) if (psiFile is PsiJavaFile) { val offender = psiFile.classes.find { differs(it) } if (offender != null) { val clsFile = offender.originalElement.containingFile?.virtualFile if (clsFile != null && !clsFile.path.matches(ANDROID_SDK_PATTERN)) { val panel = EditorNotificationPanel(LightColors.RED) panel.setText(ProjectBundle.message("library.source.mismatch", offender.name)) panel.createActionLabel(ProjectBundle.message("library.source.open.class")) { if (!project.isDisposed && clsFile.isValid) { PsiNavigationSupport.getInstance().createNavigatable(project, clsFile, -1).navigate(true) } } panel.createActionLabel(ProjectBundle.message("library.source.show.diff")) { if (!project.isDisposed && clsFile.isValid) { val cf = DiffContentFactory.getInstance() val request = SimpleDiffRequest(null, cf.create(project, clsFile), cf.create(project, file), clsFile.path, file.path) DiffManager.getInstance().showDiff(project, request) } } return panel } } } } return null } private fun differs(src: PsiClass): Boolean { val cls = src.originalElement return cls !== src && cls is PsiClass && (differs(fields(src), fields(cls), ::format) || differs(methods(src), methods(cls), ::format) || differs(inners(src), inners(cls), ::format)) } private fun <T : PsiMember> differs(srcMembers: List<T>, clsMembers: List<T>, format: (T) -> String) = srcMembers.size != clsMembers.size || srcMembers.map(format).sorted() != clsMembers.map(format).sorted() private fun fields(c: PsiClass) = if (c is PsiExtensibleClass) c.ownFields else c.fields.asList() private fun methods(c: PsiClass) = (if (c is PsiExtensibleClass) c.ownMethods else c.methods.asList()).filter { !defaultInit(it) } private fun defaultInit(it: PsiMethod) = it.isConstructor && it.parameterList.parametersCount == 0 private fun inners(c: PsiClass) = if (c is PsiExtensibleClass) c.ownInnerClasses else c.innerClasses.asList() private fun format(f: PsiField) = PsiFormatUtil.formatVariable(f, FIELD, PsiSubstitutor.EMPTY) private fun format(m: PsiMethod) = PsiFormatUtil.formatMethod(m, PsiSubstitutor.EMPTY, METHOD, PARAMETER) private fun format(c: PsiClass) = PsiFormatUtil.formatClass(c, CLASS) }
apache-2.0
77edde63c4e331fabc415409be2ae515
51.092784
140
0.736144
4.393043
false
false
false
false
carrotengineer/Warren
src/main/kotlin/engineer/carrot/warren/warren/handler/rpl/Rpl475Handler.kt
2
1209
package engineer.carrot.warren.warren.handler.rpl import engineer.carrot.warren.kale.IKaleHandler import engineer.carrot.warren.kale.irc.message.rfc1459.rpl.Rpl475Message import engineer.carrot.warren.warren.loggerFor import engineer.carrot.warren.warren.state.CaseMappingState import engineer.carrot.warren.warren.state.JoiningChannelLifecycle import engineer.carrot.warren.warren.state.JoiningChannelsState class Rpl475Handler(val channelsState: JoiningChannelsState, val caseMappingState: CaseMappingState) : IKaleHandler<Rpl475Message> { private val LOGGER = loggerFor<Rpl475Handler>() override val messageType = Rpl475Message::class.java override fun handle(message: Rpl475Message, tags: Map<String, String?>) { val channel = channelsState[message.channel] if (channel == null) { LOGGER.warn("got a bad key channel reply for a channel we don't think we're joining: $message") LOGGER.trace("channels state: $channelsState") return } LOGGER.warn("channel key wrong, failed to join: $channel") channel.status = JoiningChannelLifecycle.FAILED LOGGER.trace("new channels state: $channelsState") } }
isc
961bacf46ebf7f7e3885615695ea6592
36.78125
132
0.746071
4.428571
false
false
false
false
Doctoror/ParticleConstellationsLiveWallpaper
app/src/main/java/com/doctoror/particleswallpaper/framework/lifecycle/OnActivityResultCallback.kt
1
1202
/* * Copyright (C) 2017 Yaroslav Mytkalyk * * 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.doctoror.particleswallpaper.framework.lifecycle import android.content.Intent /** * Created by Yaroslav Mytkalyk on 31.05.17. * * onActivityResult() callback. * * This class overloads [equals] and [hashCode] to compare references instead of equality, which * allows, for example, to compare them in "contains" and "remove" methods of Collections. */ abstract class OnActivityResultCallback { abstract fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) override operator fun equals(other: Any?) = this === other override fun hashCode() = 0 }
apache-2.0
04c6e1e8241bdeddff542adf1de819c6
34.352941
96
0.740433
4.308244
false
false
false
false
WilliamHester/Breadit-2
app/app/src/main/java/me/williamhester/reddit/convert/RedditGsonConverter.kt
1
3768
package me.williamhester.reddit.convert import com.google.gson.Gson import com.google.gson.JsonElement import com.google.gson.JsonObject import me.williamhester.reddit.models.* import java.util.* /** A class for converting Gson objects to Reddit objects */ class RedditGsonConverter(private val gson: Gson) { @Throws(ConverterException::class) fun <T> toList(element: JsonElement): List<T> = toList(element.asJsonObject, 0) @Throws(ConverterException::class) private fun <T> toList(jsonObject: JsonObject, level: Int = 0): List<T> { if (jsonObject.get("kind").asString != "Listing") { throw ConverterException(jsonObject, "Listing") } val children = jsonObject .get("data") .asJsonObject .get("children") .asJsonArray val things = LinkedList<Any?>() for (e in children) { val obj = e.asJsonObject val type = getKind(obj) when (type) { "t1" -> toTextComment(things, obj, level) "t2" -> things.add(toAccount(obj)) "t3" -> things.add(toSubmission(obj)) "t4" -> {} // things.add(toMessage(jsonObject)) "t5" -> things.add(toSubreddit(obj)) "more" -> things.add(toMoreComment(obj, level)) else -> throw ConverterException(obj, "") } } @Suppress("UNCHECKED_CAST") // Yeah, it's dangerous. Sue me. return things as List<T> } @Throws(ConverterException::class) fun toPost(element: JsonElement): Post { if (!element.isJsonArray) { throw ConverterException(element, "Array containing a submission and a list of comments") } val array = element.asJsonArray val submission = toList<Votable>(array.get(0))[0] as Submission val comments = toList<Comment>(array.get(1)) return Post(submission, comments) } /** * Converts the [JsonObject] to a [Account] */ fun toAccount(`object`: JsonObject): Account? { return null } /** * Converts the [JsonObject] to a [Edited] */ fun toEdited(`object`: JsonObject): Edited? { return null } /** * Converts the [JsonObject] to a [MoreComment] */ fun toMoreComment(`object`: JsonObject, level: Int): MoreComment { return MoreComment( gson.fromJson(`object`.get("data"), MoreCommentJson::class.java), level) } /** * Converts the [JsonObject] to a [Submission] */ fun toSubmission(`object`: JsonObject): Submission { return Submission(gson.fromJson(getData(`object`), SubmissionJson::class.java)) } /** * Converts the [JsonObject] to a [TextComment] */ @Throws(ConverterException::class) @JvmOverloads fun toTextComment(comments: MutableList<Any?>, `object`: JsonObject, level: Int = 0): TextComment { val data = getData(`object`) val comment = TextComment(gson.fromJson(data, TextCommentJson::class.java), level) comments.add(comment) val replies = data.get("replies") if (replies != null && replies.isJsonObject) { comments.addAll(toList(replies.asJsonObject, level + 1)) } return comment } /** Converts the [JsonObject] to a [Votable] */ fun toVotable(obj: JsonObject): Votable? = null /** Converts the [JsonObject] to a [VoteStatus] */ fun toVoteStatus(obj: JsonObject): VoteStatus? = null fun toSubreddit(obj: JsonElement) = Subreddit(gson.fromJson(obj.asJsonObject.get("data"), SubredditJson::class.java)) fun toAccessTokenJson(obj: JsonElement): AccessTokenJson = gson.fromJson(obj, AccessTokenJson::class.java) fun toMeResponse(obj: JsonElement): MeResponse = gson.fromJson(obj, MeResponse::class.java) private fun getKind(o: JsonObject): String { return o.get("kind").asString } private fun getData(o: JsonObject): JsonObject { return o.get("data").asJsonObject } }
apache-2.0
bb94069e13d9fd52c7c4c5803c46b026
29.144
119
0.666667
3.925
false
false
false
false
AshishKayastha/Movie-Guide
app/src/main/kotlin/com/ashish/movieguide/ui/discover/filter/FilterBottomSheetDialogFragment.kt
1
8366
package com.ashish.movieguide.ui.discover.filter import android.app.DatePickerDialog import android.os.Bundle import android.support.design.widget.BottomSheetDialogFragment import android.support.v7.widget.GridLayoutManager import android.support.v7.widget.RecyclerView import android.support.v7.widget.StaggeredGridLayoutManager import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.RadioButton import android.widget.RadioGroup import com.ashish.movieguide.R import com.ashish.movieguide.app.MovieGuideApp import com.ashish.movieguide.data.models.FilterQuery import com.ashish.movieguide.di.multibindings.fragment.FragmentComponentBuilderHost import com.ashish.movieguide.ui.widget.FontButton import com.ashish.movieguide.ui.widget.FontTextView import com.ashish.movieguide.ui.widget.ItemOffsetDecoration import com.ashish.movieguide.utils.Constants.DATE_PICKER_FORMAT import com.ashish.movieguide.utils.Constants.SORT_BY_MOVIE import com.ashish.movieguide.utils.Constants.SORT_BY_TV_SHOW import com.ashish.movieguide.utils.extensions.bindView import com.ashish.movieguide.utils.extensions.convertToDate import com.ashish.movieguide.utils.extensions.dpToPx import com.ashish.movieguide.utils.extensions.get import com.ashish.movieguide.utils.extensions.getExtrasOrRestore import com.ashish.movieguide.utils.extensions.getFormattedDate import com.ashish.movieguide.utils.extensions.hide import com.ashish.movieguide.utils.extensions.isValidDate import com.ashish.movieguide.utils.extensions.showToast import icepick.Icepick import icepick.State import java.util.Calendar import java.util.Date import java.util.Locale import javax.inject.Inject /** * Created by Ashish on Jan 07. */ class FilterBottomSheetDialogFragment : BottomSheetDialogFragment() { companion object { private const val ARG_IS_MOVIE = "is_movie" private const val ARG_FILTER_QUERY = "filter_query" @JvmStatic fun newInstance(isMovie: Boolean, filterQuery: FilterQuery): FilterBottomSheetDialogFragment { val args = Bundle() args.putBoolean(ARG_IS_MOVIE, isMovie) args.putParcelable(ARG_FILTER_QUERY, filterQuery) val fragment = FilterBottomSheetDialogFragment() fragment.arguments = args return fragment } } @Inject lateinit var filterQueryModel: FilterQueryModel @JvmField @State var isMovie: Boolean = true @JvmField @State var filterQuery: FilterQuery? = null private val endDateText: FontTextView by bindView(R.id.end_date_text) private val applyFilterBtn: FontButton by bindView(R.id.apply_filter_btn) private val startDateText: FontTextView by bindView(R.id.start_date_text) private val sortByRadioGroup: RadioGroup by bindView(R.id.sort_radio_group) private val genreRecyclerView: RecyclerView by bindView(R.id.genre_recycler_view) private val calendar = Calendar.getInstance() private lateinit var genreAdapter: GenreAdapter private var endDatePickerDialog: DatePickerDialog? = null private var startDatePickerDialog: DatePickerDialog? = null private val startDateSetListener = DatePickerDialog.OnDateSetListener { _, year, month, dayOfMonth -> setFormattedDate(year, month, dayOfMonth, true) } private val endDateSetListener = DatePickerDialog.OnDateSetListener { _, year, month, dayOfMonth -> setFormattedDate(year, month, dayOfMonth, false) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) (targetFragment as FragmentComponentBuilderHost) .getFragmentComponentBuilder(FilterBottomSheetDialogFragment::class.java, FilterComponent.Builder::class.java) .build() .inject(this) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(R.layout.fragment_bottom_sheet_filter, container, false) } override fun onViewCreated(view: View?, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) savedInstanceState.getExtrasOrRestore(this) { getFragmentArguments() } if (isMovie) { genreAdapter = GenreAdapter(activity, R.array.movie_genre_list, R.array.movie_genre_id_list, filterQuery?.genreIds) } else { genreAdapter = GenreAdapter(activity, R.array.tv_genre_list, R.array.tv_genre_id_list, filterQuery?.genreIds) } genreRecyclerView.apply { addItemDecoration(ItemOffsetDecoration(8f.dpToPx().toInt())) layoutManager = StaggeredGridLayoutManager(2, GridLayoutManager.HORIZONTAL) adapter = genreAdapter } val sortByIndex: Int if (isMovie) { sortByIndex = SORT_BY_MOVIE.indexOf(filterQuery?.sortBy) } else { // Hide sort by title RadioButton for TV Shows sortByRadioGroup.weightSum = 3f sortByRadioGroup[2]?.hide() sortByIndex = SORT_BY_TV_SHOW.indexOf(filterQuery?.sortBy) } (sortByRadioGroup[sortByIndex] as RadioButton?)?.isChecked = true applyFilterBtn.setOnClickListener { if (isValidDate(filterQuery?.minDate, filterQuery?.maxDate)) { updateFilterQuery() filterQueryModel.setFilterQuery(filterQuery!!) dismiss() } else { activity.showToast(R.string.error_choose_valid_date) } } initDatePicker(filterQuery?.minDate.convertToDate(), true) initDatePicker(filterQuery?.maxDate.convertToDate(), false) startDateText.setOnClickListener { startDatePickerDialog?.show() } endDateText.setOnClickListener { endDatePickerDialog?.show() } } private fun getFragmentArguments() { arguments.apply { isMovie = getBoolean(ARG_IS_MOVIE) filterQuery = getParcelable(ARG_FILTER_QUERY) } } private fun initDatePicker(date: Date?, isStartDate: Boolean) { if (date != null) calendar.time = date val year = calendar.get(Calendar.YEAR) val month = calendar.get(Calendar.MONTH) val dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH) if (isStartDate) { startDatePickerDialog = DatePickerDialog(activity, startDateSetListener, year, month, dayOfMonth) } else { endDatePickerDialog = DatePickerDialog(activity, endDateSetListener, year, month, dayOfMonth) } if (date != null) { setFormattedDate(year, month, dayOfMonth, isStartDate) } } private fun setFormattedDate(year: Int, month: Int, dayOfMonth: Int, isStartDate: Boolean) { val datePickerDate = getFormattedDatePickerDate(year, month, dayOfMonth) if (isStartDate) { filterQuery?.minDate = datePickerDate startDateText.text = datePickerDate.getFormattedDate() } else { filterQuery?.maxDate = datePickerDate endDateText.text = datePickerDate.getFormattedDate() } } private fun getFormattedDatePickerDate(year: Int, month: Int, dayOfMonth: Int): String { return String.format(Locale.getDefault(), DATE_PICKER_FORMAT, year, month + 1, dayOfMonth) } private fun updateFilterQuery() { val radioButton = sortByRadioGroup.findViewById(sortByRadioGroup.checkedRadioButtonId) val sortByIndex = sortByRadioGroup.indexOfChild(radioButton) if (isMovie) { filterQuery?.sortBy = SORT_BY_MOVIE[sortByIndex] } else { filterQuery?.sortBy = SORT_BY_TV_SHOW[sortByIndex] } filterQuery?.genreIds = genreAdapter.getSelectedGenreIds() } override fun onSaveInstanceState(outState: Bundle?) { updateFilterQuery() Icepick.saveInstanceState(this, outState) super.onSaveInstanceState(outState) } override fun onDestroyView() { genreRecyclerView.adapter = null super.onDestroyView() } override fun onDestroy() { super.onDestroy() MovieGuideApp.getRefWatcher(activity).watch(this) } }
apache-2.0
03b387ae44e551947f80a4c039ab1879
37.736111
116
0.70141
4.718556
false
false
false
false
McMoonLakeDev/MoonLake
API/src/main/kotlin/com/mcmoonlake/api/particle/Particle.kt
1
27895
/* * 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.particle import com.mcmoonlake.api.currentMCVersion import com.mcmoonlake.api.isOrLater import com.mcmoonlake.api.packet.PacketOutParticles import com.mcmoonlake.api.version.IllegalBukkitVersionException import com.mcmoonlake.api.version.MinecraftVersion import org.bukkit.Location import org.bukkit.Material import org.bukkit.entity.Player import org.bukkit.util.Vector /** * @author # [DarkBlade12](https://github.com/DarkBlade12) by origin, [lgou2w](https://github.com/lgou2w) by modified. */ enum class Particle { /** * Particle: Explosion, Version: All | Requires: Directional (粒子效果: 普通爆炸, 版本: 全版本 | 需求: 矢量方向) * - [Wiki](https://minecraft.gamepedia.com/Particle#explode) */ EXPLOSION_NORMAL("explode", 0, ParticleProperty.DIRECTIONAL), /** * Particle: Large Explode, Version: All (粒子效果: 大型爆炸, 版本: 全版本) * - [Wiki](https://minecraft.gamepedia.com/Particle#largeexplode) */ EXPLOSION_LARGE("largeexplode", 1), /** * Particle: Huge Explosion, Version: All (粒子效果: 巨大爆炸, 版本: 全版本) * - [Wiki](https://minecraft.gamepedia.com/Particle#hugeexplosion) */ EXPLOSION_HUGE("hugeexplosion", 2), /** * Particle: Fireworks Spark, Version: All (粒子效果: 烟花尾迹, 版本: 全版本) * - [Wiki](https://minecraft.gamepedia.com/Particle#fireworksSpark) */ FIREWORKS_SPARK("fireworksSpark", 3, ParticleProperty.DIRECTIONAL), /** * Particle: Water Bubble, Version: All | Requires: Directional, Water (粒子效果: 水泡, 版本: 全版本 | 需求: 矢量方向, 需求: 水源) * - [Wiki](https://minecraft.gamepedia.com/Particle#bubble) */ WATER_BUBBLE("bubble", 4, ParticleProperty.DIRECTIONAL, ParticleProperty.REQUIRES_WATER), /** * Particle: Water Splash, Version: All | Requires: Directional (粒子效果: 水花溅起, 版本: 全版本 | 需求: 矢量方向) * - [Wiki](https://minecraft.gamepedia.com/Particle#splash) */ WATER_SPLASH("splash", 5, ParticleProperty.DIRECTIONAL), /** * Particle: Water Wake, Version: All | Requires: Directional (粒子效果: 水尾波, 版本: 全版本 | 需求: 矢量方向) * - [Wiki](https://minecraft.gamepedia.com/Particle#) */ WATER_WAKE("wake", 6, ParticleProperty.DIRECTIONAL), /** * Particle: Suspended, Version: All | Requires: Water (粒子效果: 水下颗粒, 版本: 全版本 | 需求: 水源) * - [Wiki](https://minecraft.gamepedia.com/Particle#suspended) */ SUSPENDED("suspended", 7, ParticleProperty.REQUIRES_WATER), /** * Particle: Suspended Depth, Version: All | Requires: Directional (粒子效果: 虚空颗粒, 版本: 全版本 | 需求: 矢量方向) * - [Wiki](https://minecraft.gamepedia.com/Particle#depthSuspended) */ SUSPENDED_DEPTH("depthSuspended", 8, ParticleProperty.DIRECTIONAL), /** * Particle: Crit, Version: All | Requires: Directional (粒子效果: 暴击, 版本: 全版本 | 需求: 矢量方向) * - [Wiki](https://minecraft.gamepedia.com/Particle#crit) */ CRIT("crit", 9, ParticleProperty.DIRECTIONAL), /** * Particle: Magic Crit, Version: All | Requires: Directional (粒子效果: 魔法暴击, 版本: 全版本 | 需求: 矢量方向) * - [Wiki](https://minecraft.gamepedia.com/Particle#) */ CRIT_MAGIC("magicCrit", 10, ParticleProperty.DIRECTIONAL), /** * Particle: Smoke, Version: All | Requires: Directional (粒子效果: 烟雾, 版本: 全版本 | 需求: 矢量方向) * - [Wiki](https://minecraft.gamepedia.com/Particle#smoke) */ SMOKE_NORMAL("smoke", 11, ParticleProperty.DIRECTIONAL), /** * Particle: Large Smoke, Version: All | Requires: Directional (粒子效果: 大型烟雾, 版本: 全版本 | 需求: 矢量方向) * - [Wiki](https://minecraft.gamepedia.com/Particle#largesmoke) */ SMOKE_LARGE("largesmoke", 12, ParticleProperty.DIRECTIONAL), /** * Particle: Spell, Version: All (粒子效果: 药水符咒, 版本: 全版本) * - [Wiki](https://minecraft.gamepedia.com/Particle#spell) */ SPELL("spell", 13), /** * Particle: Instant Spell, Version: All (粒子效果: 瞬间药水符咒, 版本: 全版本) * - [Wiki](https://minecraft.gamepedia.com/Particle#instantSpell) */ SPELL_INSTANT("instantSpell", 14), /** * Particle: Mob Spell, Version: All | Requires: Color (粒子效果: 实体药水符咒, 版本: 全版本 | 需求: 颜色) * - [Wiki](https://minecraft.gamepedia.com/Particle#mobSpell) */ SPELL_MOB("mobSpell", 15, ParticleProperty.COLOR), /** * Particle: Mob Spell Ambient, Version: All | Requires: Color (粒子效果: 实体药水符咒环境, 版本: 全版本 | 需求: 颜色) * - [Wiki](https://minecraft.gamepedia.com/Particle#mobSpellAmbient) */ SPELL_MOB_AMBIENT("mobSpellAmbient", 16, ParticleProperty.COLOR), /** * Particle: Witch Magic, Version: All (粒子效果: 女巫魔法, 版本: 全版本) * - [Wiki](https://minecraft.gamepedia.com/Particle#witchMagic) */ SPELL_WITCH("witchMagic", 17), /** * Particle: Drip Water, Version: All (粒子效果: 滴水, 版本: 全版本) * - [Wiki](https://minecraft.gamepedia.com/Particle#dripWater) */ DRIP_WATER("dripWater", 18), /** * Particle: Drip Lava, Version: All (粒子效果: 滴岩浆, 版本: 全版本) * - [Wiki](https://minecraft.gamepedia.com/Particle#dripLava) */ DRIP_LAVA("dripLava", 19), /** * Particle: Villager Angry, Version: All (粒子效果: 村民生气, 版本: 全版本) * - [Wiki](https://minecraft.gamepedia.com/Particle#angryVillager) */ VILLAGER_ANGRY("angryVillager", 20), /** * Particle: Villager Happy, Version: All | Requires: Directional (粒子效果: 村民高兴, 版本: 全版本 | 需求: 矢量方向) * - [Wiki](https://minecraft.gamepedia.com/Particle#happyVillager) */ VILLAGER_HAPPY("happyVillager", 21, ParticleProperty.DIRECTIONAL), /** * Particle: Town Aura, Version: All (粒子效果: 菌丝颗粒, 版本: 全版本) * - [Wiki](https://minecraft.gamepedia.com/Particle#townAura) */ TOWN_AURA("townAura", 22), /** * Particle: Note, Version: All | Requires: Color (粒子效果: 音符, 版本: 全版本 | 需求: 颜色) * - [Wiki](https://minecraft.gamepedia.com/Particle#note) */ NOTE("note", 23, ParticleProperty.COLOR), /** * Particle: Portal, Version: All | Requires: Directional (粒子效果: 传送门, 版本: 全版本 | 需求: 矢量方向) * - [Wiki](https://minecraft.gamepedia.com/Particle#portal) */ PORTAL("portal", 24, ParticleProperty.DIRECTIONAL), /** * Particle: Enchantment Table, Version: All | Requires: Directional (粒子效果: 附魔台, 版本: 全版本 | 需求: 矢量方向) * - [Wiki](https://minecraft.gamepedia.com/Particle#enchantmenttable) */ ENCHANTMENT_TABLE("enchantmenttable", 25, ParticleProperty.DIRECTIONAL), /** * Particle: Flame, Version: All | Requires: Directional (粒子效果: 火焰, 版本: 全版本 | 需求: 矢量方向) * - [Wiki](https://minecraft.gamepedia.com/Particle#flame) */ FLAME("flame", 26, ParticleProperty.DIRECTIONAL), /** * Particle: Lava, Version: All (粒子效果: 岩浆, 版本: 全版本) * - [Wiki](https://minecraft.gamepedia.com/Particle#lava) */ LAVA("lava", 27), /** * Particle: Footstep, Version: All (粒子效果: 脚印, 版本: 全版本) * - [Wiki](https://minecraft.gamepedia.com/Particle#footstep) */ FOOTSTEP("footstep", 28), /** * Particle: Cloud, Version: All | Requires: Directional (粒子效果: 云, 版本: 全版本 | 需求: 矢量方向) * - [Wiki](https://minecraft.gamepedia.com/Particle#cloud) */ CLOUD("cloud", 29, ParticleProperty.DIRECTIONAL), /** * Particle: Red Dust, Version: All | Requires: Color (粒子效果: 红尘, 版本: 全版本 | 需求: 颜色) * - [Wiki](https://minecraft.gamepedia.com/Particle#reddust) */ RED_DUST("reddust", 30, ParticleProperty.COLOR), /** * Particle: Snow Ball, Version: All (粒子效果: 雪球碎裂, 版本: 全版本) * - [Wiki](https://minecraft.gamepedia.com/Particle#snowballpoof) */ SNOWBALL("snowballpoof", 31), /** * Particle: Snow Shovel, Version: All | Requires: Directional (粒子效果: 雪颗粒, 版本: 全版本 | 需求: 矢量方向) * - [Wiki](https://minecraft.gamepedia.com/Particle#snowshovel) */ SNOW_SHOVEL("snowshovel", 32, ParticleProperty.DIRECTIONAL), /** * Particle: Slime, Version: All (粒子效果: 史莱姆, 版本: 全版本) * - [Wiki](https://minecraft.gamepedia.com/Particle#slime) */ SLIME("slime", 33), /** * Particle: Heart, Version: All (粒子效果: 爱心, 版本: 全版本) * - [Wiki](https://minecraft.gamepedia.com/Particle#heart) */ HEART("heart", 34), /** * Particle: Barrier, Version: 1.8+ (粒子效果: 屏障, 版本: 1.8+) * - [Wiki](https://minecraft.gamepedia.com/Particle#barrier) */ BARRIER("barrier", 35, MinecraftVersion.V1_8), /** * Particle: Item Crack, Version: All | Requires: Directional, Data (粒子效果: 物品碎裂, 版本: 全版本 | 需求: 矢量方向, 需求: 数据) * - [Wiki](https://minecraft.gamepedia.com/Particle#iconcrack) */ ITEM_CRACK("iconcrack", 36, 2, null, ParticleProperty.DIRECTIONAL, ParticleProperty.REQUIRES_DATA), /** * Particle: Block Crack, Version: All | Requires: Data (粒子效果: 方块碎裂, 版本: 全版本 | 需求: 数据) * - [Wiki](https://minecraft.gamepedia.com/Particle#blockcrack) */ BLOCK_CRACK("blockcrack", 37, 1, null, ParticleProperty.REQUIRES_DATA), /** * Particle: Block Dust, Version: All | Requires: Directional, Data (粒子效果: 方块尘, 版本: 全版本 | 需求: 矢量方向, 需求: 数据) * - [Wiki](https://minecraft.gamepedia.com/Particle#blockdust) */ BLOCK_DUST("blockdust", 38, 1, null, ParticleProperty.DIRECTIONAL, ParticleProperty.REQUIRES_DATA), /** * Particle: Water Drop, Version: 1.8+ (粒子效果: 雨滴, 版本: 1.8+) * - [Wiki](https://minecraft.gamepedia.com/Particle#droplet) */ WATER_DROP("droplet", 39, MinecraftVersion.V1_8), /** * Particle: Item Take, Version: 1.8+ (粒子效果: 物品获取, 版本: 1.8+) * - [Wiki](https://minecraft.gamepedia.com/Particle#take) */ ITEM_TAKE("take", 40, MinecraftVersion.V1_8), /** * Particle: Mob Appearance, Version: 1.8+ (粒子效果: 远古守护者, 版本: 1.8+) * - [Wiki](https://minecraft.gamepedia.com/Particle#mobappearance) */ MOB_APPEARANCE("mobappearance", 41, MinecraftVersion.V1_8), /** * Particle: Dragon Breath, Version: 1.9+ (粒子效果: 龙息, 版本: 1.9+) * - [Wiki](https://minecraft.gamepedia.com/Particle#dragonbreath) */ DRAGON_BREATH("dragonbreath", 42, MinecraftVersion.V1_9), /** * Particle: End Rod, Version: 1.9+ (粒子效果: 末地烛, 版本: 1.9+) * - [Wiki](https://minecraft.gamepedia.com/Particle#endRod) */ END_ROD("endRod", 43, MinecraftVersion.V1_9), /** * Particle: Damage Indicator, Version: 1.9+ (粒子效果: 伤害指示器, 版本: 1.9+) * - [Wiki](https://minecraft.gamepedia.com/Particle#damageIndicator) */ DAMAGE_INDICATOR("damageIndicator", 44, MinecraftVersion.V1_9), /** * Particle: Sweep Attack, Version: 1.9+ (粒子效果: 扫荡攻击, 版本: 1.9+) * - [Wiki](https://minecraft.gamepedia.com/Particle#sweepAttack) */ SWEEP_ATTACK("sweepAttack", 45, MinecraftVersion.V1_9), /** * Particle: Falling Dust, Version: 1.9+ | Requires: Data (粒子效果: 掉落尘, 版本: 1.9+ | 需求: 数据) * - [Wiki](https://minecraft.gamepedia.com/Particle#fallingdust) */ FALLING_DUST("fallingdust", 46, 1, MinecraftVersion.V1_10, ParticleProperty.REQUIRES_DATA), /** * Particle: Totem, Version: 1.11+ (粒子效果: 不死图腾颗粒, 版本: 1.11+) * - [Wiki](https://minecraft.gamepedia.com/Particle#totem) */ TOTEM("totem", 47, MinecraftVersion.V1_11), /** * Particle: Spit, Version: 1.11+ (粒子效果: 羊驼口水, 版本: 1.11+) * - [Wiki](https://minecraft.gamepedia.com/Particle#spit) */ SPIT("spit", 48, MinecraftVersion.V1_11), ; /** member */ val id: Int val type: String val dataLength: Int val mcVer: MinecraftVersion? private val properties: Array<out ParticleProperty> /** constructor */ constructor(type: String, id: Int, vararg properties: ParticleProperty) : this(type, id, null, *properties) constructor(type: String, id: Int, mcVer: MinecraftVersion? = null, vararg properties: ParticleProperty) : this(type, id, 0, mcVer, *properties) constructor(type: String, id: Int, dataLength: Int = 0, mcVer: MinecraftVersion? = null, vararg properties: ParticleProperty) { this.id = id this.type = type this.mcVer = mcVer this.properties = properties this.dataLength = dataLength } /** api */ fun hasProperty(property: ParticleProperty): Boolean = properties.contains(property) fun isSupported() = mcVer == null || currentMCVersion().isOrLater(mcVer) @Throws(ParticleException::class) fun display(offsetX: Float, offsetY: Float, offsetZ: Float, speed: Float, amount: Int, center: Location, range: Double) { if(!isSupported()) throw ParticleException(IllegalBukkitVersionException("粒子效果 $this 不支持当前服务端版本. $mcVer")) if(hasProperty(ParticleProperty.REQUIRES_DATA)) throw ParticleException("粒子效果 $this 要求添加粒子数据属性.") if(hasProperty(ParticleProperty.REQUIRES_WATER) && !isWater(center)) throw ParticleException("粒子效果没有水源在中心位置.") ParticlePacket(this, offsetX, offsetY, offsetZ, speed, amount, range > 256.0, null).sendTo(center, range) } @Throws(ParticleException::class) fun display(offsetX: Float, offsetY: Float, offsetZ: Float, speed: Float, amount: Int, center: Location, players: List<Player>) { if(!isSupported()) throw ParticleException(IllegalBukkitVersionException("粒子效果 $this 不支持当前服务端版本. $mcVer")) if(hasProperty(ParticleProperty.REQUIRES_DATA)) throw ParticleException("粒子效果 $this 要求添加粒子数据属性.") if(hasProperty(ParticleProperty.REQUIRES_WATER) && !isWater(center)) throw ParticleException("粒子效果没有水源在中心位置.") ParticlePacket(this, offsetX, offsetY, offsetZ, speed, amount, isLongDistance(center, players), null).sendTo(center, players) } @Throws(ParticleException::class) fun display(offsetX: Float, offsetY: Float, offsetZ: Float, speed: Float, amount: Int, center: Location, vararg players: Player) = display(offsetX, offsetY, offsetZ, speed, amount, center, players.toList()) @Throws(ParticleException::class) fun display(direction: Vector, speed: Float, center: Location, range: Double) { if(!isSupported()) throw ParticleException(IllegalBukkitVersionException("粒子效果 $this 不支持当前服务端版本. $mcVer")) if(hasProperty(ParticleProperty.REQUIRES_DATA)) throw ParticleException("粒子效果 $this 要求添加粒子数据属性.") if(!hasProperty(ParticleProperty.DIRECTIONAL)) throw ParticleException("粒子效果没有矢量方向属性.") if(hasProperty(ParticleProperty.REQUIRES_WATER) && !isWater(center)) throw ParticleException("粒子效果没有水源在中心位置.") ParticlePacket(this, direction, speed, range > 256.0, null).sendTo(center, range) } @Throws(ParticleException::class) fun display(direction: Vector, speed: Float, center: Location, players: List<Player>) { if(!isSupported()) throw ParticleException(IllegalBukkitVersionException("粒子效果 $this 不支持当前服务端版本. $mcVer")) if(hasProperty(ParticleProperty.REQUIRES_DATA)) throw ParticleException("粒子效果 $this 要求添加粒子数据属性.") if(!hasProperty(ParticleProperty.DIRECTIONAL)) throw ParticleException("粒子效果没有矢量方向属性.") if(hasProperty(ParticleProperty.REQUIRES_WATER) && !isWater(center)) throw ParticleException("粒子效果没有水源在中心位置.") ParticlePacket(this, direction, speed, isLongDistance(center, players), null).sendTo(center, players) } @Throws(ParticleException::class) fun display(direction: Vector, speed: Float, center: Location, vararg players: Player) = display(direction, speed, center, players.toList()) @Throws(ParticleException::class) fun display(color: ParticleColor, center: Location, range: Double) { if(!isSupported()) throw ParticleException(IllegalBukkitVersionException("粒子效果 $this 不支持当前服务端版本. $mcVer")) if(!hasProperty(ParticleProperty.COLOR)) throw ParticleException("粒子效果没有颜色值属性.") if(!isColorCorrect(this, color)) throw ParticleException("粒子效果和效果颜色对象不符合.") ParticlePacket(this, color, range > 256.0).sendTo(center, range) } @Throws(ParticleException::class) fun display(color: ParticleColor, center: Location, players: List<Player>) { if(!isSupported()) throw ParticleException(IllegalBukkitVersionException("粒子效果 $this 不支持当前服务端版本. $mcVer")) if(!hasProperty(ParticleProperty.COLOR)) throw ParticleException("粒子效果没有颜色值属性.") if(!isColorCorrect(this, color)) throw ParticleException("粒子效果和效果颜色对象不符合.") ParticlePacket(this, color, isLongDistance(center, players)).sendTo(center, players) } @Throws(ParticleException::class) fun display(color: ParticleColor, center: Location, vararg players: Player) = display(color, center, players.toList()) @Throws(ParticleException::class) fun display(data: ParticleData, offsetX: Float, offsetY: Float, offsetZ: Float, speed: Float, amount: Int, center: Location, range: Double) { if(!isSupported()) throw ParticleException(IllegalBukkitVersionException("粒子效果 $this 不支持当前服务端版本. $mcVer")) if(!hasProperty(ParticleProperty.REQUIRES_DATA)) throw ParticleException("粒子效果没有粒子数据属性.") if(!isDataCorrect(this, data)) throw ParticleException("粒子效果 $this 和粒子数据对象 $data 不符合.") ParticlePacket(this, offsetX, offsetY, offsetZ, speed, amount, range > 256.0, data).sendTo(center, range) } @Throws(ParticleException::class) fun display(data: ParticleData, offsetX: Float, offsetY: Float, offsetZ: Float, speed: Float, amount: Int, center: Location, players: List<Player>) { if(!isSupported()) throw ParticleException(IllegalBukkitVersionException("粒子效果 $this 不支持当前服务端版本. $mcVer")) if(!hasProperty(ParticleProperty.REQUIRES_DATA)) throw ParticleException("粒子效果没有粒子数据属性.") if(!isDataCorrect(this, data)) throw ParticleException("粒子效果 $this 和粒子数据对象 $data 不符合.") ParticlePacket(this, offsetX, offsetY, offsetZ, speed, amount, isLongDistance(center, players), data).sendTo(center, players) } @Throws(ParticleException::class) fun display(data: ParticleData, offsetX: Float, offsetY: Float, offsetZ: Float, speed: Float, amount: Int, center: Location, vararg players: Player) = display(data, offsetX, offsetY, offsetZ, speed, amount, center, players.toList()) @Throws(ParticleException::class) fun display(data: ParticleData, direction: Vector, speed: Float, center: Location, range: Double) { if(!isSupported()) throw ParticleException(IllegalBukkitVersionException("粒子效果 $this 不支持当前服务端版本. $mcVer")) if(!hasProperty(ParticleProperty.REQUIRES_DATA)) throw ParticleException("粒子效果没有粒子数据属性.") if(!isDataCorrect(this, data)) throw ParticleException("粒子效果 $this 和粒子数据对象 $data 不符合.") ParticlePacket(this, direction, speed, range > 256.0, data).sendTo(center, range) } @Throws(ParticleException::class) fun display(data: ParticleData, direction: Vector, speed: Float, center: Location, players: List<Player>) { if(!isSupported()) throw ParticleException(IllegalBukkitVersionException("粒子效果 $this 不支持当前服务端版本. $mcVer")) if(!hasProperty(ParticleProperty.REQUIRES_DATA)) throw ParticleException("粒子效果没有粒子数据属性.") if(!isDataCorrect(this, data)) throw ParticleException("粒子效果 $this 和粒子数据对象 $data 不符合.") ParticlePacket(this, direction, speed, isLongDistance(center, players), data).sendTo(center, players) } @Throws(ParticleException::class) fun display(data: ParticleData, direction: Vector, speed: Float, center: Location, vararg players: Player) = display(data, direction, speed, center, players.toList()) @Throws(ParticleException::class) fun display(center: Location, range: Double, offsetX: Float, offsetY: Float, offsetZ: Float, speed: Float, amount: Int) = display(offsetX, offsetY, offsetZ, speed, amount, center, range) @Throws(ParticleException::class) fun display(center: Location, range: Double) = display(0f, 0f, 0f, 0f, 1, center, range) @Throws(ParticleException::class) fun display(data: ParticleData, center: Location, range: Double, offsetX: Float, offsetY: Float, offsetZ: Float, speed: Float, amount: Int) { when(hasProperty(ParticleProperty.REQUIRES_DATA)) { true -> display(data, offsetX, offsetY, offsetZ, speed, amount, center, range) else -> display(offsetX, offsetY, offsetZ, speed, amount, center, range) } } /** static */ companion object { @JvmStatic private val ID_MAP: MutableMap<Int, Particle> = HashMap() init { values().forEach { ID_MAP[it.id] = it } } @JvmStatic @JvmName("isWater") private fun isWater(location: Location): Boolean = location.block.type.let { it == Material.WATER || it == Material.STATIONARY_WATER } @JvmStatic @JvmName("isLongDistance") private fun isLongDistance(location: Location, players: List<Player>): Boolean = players.let { val world = location.world.name return it.any { world == it.world.name && it.location.distanceSquared(location) <= 65536.0 } } @JvmStatic @JvmName("isDataCorrect") private fun isDataCorrect(particle: Particle, data: ParticleData): Boolean = (particle == BLOCK_CRACK || particle == BLOCK_DUST) && data is ParticleDataBlock || particle == ITEM_CRACK && data is ParticleDataItem @JvmStatic @JvmName("isColorCorrect") private fun isColorCorrect(particle: Particle, color: ParticleColor): Boolean = (particle == SPELL_MOB || particle == SPELL_MOB_AMBIENT || particle == RED_DUST) && color is ParticleColorOrdinary || particle == NOTE && color is ParticleColorNote @JvmStatic @JvmName("fromId") fun fromId(id: Int): Particle = ID_MAP[id] ?: Particle.BARRIER } /** inner class */ private inner class ParticlePacket { /** member */ private val particle: Particle private var offsetX: Float private val offsetY: Float private val offsetZ: Float private val speed: Float private val amount: Int private val longDistance: Boolean private val data: ParticleData? /** constructor */ constructor(particle: Particle, offsetX: Float, offsetY: Float, offsetZ: Float, speed: Float, amount: Int, longDistance: Boolean, data: ParticleData? = null) { this.particle = particle this.offsetX = offsetX this.offsetY = offsetY this.offsetZ = offsetZ this.speed = if(speed < 0f) 1f else speed this.amount = if(amount < 0) 1 else amount this.longDistance = longDistance this.data = data } constructor(particle: Particle, direction: Vector, speed: Float, longDistance: Boolean, data: ParticleData? = null) { this.particle = particle this.offsetX = direction.x.toFloat() this.offsetY = direction.y.toFloat() this.offsetZ = direction.z.toFloat() this.speed = if(speed < 0f) 1.0f else speed this.amount = 1 this.longDistance = longDistance this.data = data } constructor(particle: Particle, color: ParticleColor, longDistance: Boolean) : this(particle, color.valueX, color.valueY, color.valueZ, 1f, 0, longDistance, null) { if(particle == RED_DUST && color is ParticleColorOrdinary && color.red == 0) offsetX = java.lang.Float.MIN_NORMAL } /** api */ fun sendTo(center: Location, range: Double) = createPacket(center).sendToNearby(center, range) fun sendTo(center: Location, players: List<Player>) = createPacket(center).send(players.toTypedArray()) /** implement */ private fun createPacket(center: Location): PacketOutParticles { val arguments = ArrayList<Int>() if(data != null) when(particle) { ITEM_CRACK -> arguments.addAll(data.packetData) else -> arguments.add(data.packetData[0].or(data.packetData[1].shl(12))) } return PacketOutParticles( particle, longDistance, center.x.toFloat(), center.y.toFloat(), center.z.toFloat(), offsetX, offsetY, offsetZ, speed, amount, arguments) } } }
gpl-3.0
c2a765b3da3bc682cec6361add9b7ce6
40.096308
182
0.641253
3.470652
false
false
false
false
mikepenz/FastAdapter
fastadapter-extensions-scroll/src/main/java/com/mikepenz/fastadapter/scroll/EndlessRecyclerOnTopScrollListener.kt
1
5992
package com.mikepenz.fastadapter.scroll import android.view.View import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.OrientationHelper import androidx.recyclerview.widget.RecyclerView import com.mikepenz.fastadapter.FastAdapter abstract class EndlessRecyclerOnTopScrollListener : RecyclerView.OnScrollListener { private var previousTotal = 0 private var isLoading = true private var adapter: FastAdapter<*>? = null private var orientationHelper: OrientationHelper? = null private var isOrientationHelperVertical: Boolean = false private var alreadyCalledOnNoMore: Boolean = false private lateinit var _layoutManager: LinearLayoutManager var currentPage = 0 private set var firstVisibleItem: Int = 0 private set var visibleItemCount: Int = 0 private set var totalItemCount: Int = 0 private set var visibleThreshold = RecyclerView.NO_POSITION // how many items your adapter must have at the end? // leave it -1 as its by default to disable onNothingToLoad() feature if you have only local data var totalLoadedItems = -1 val isNothingToLoadFeatureEnabled: Boolean get() = totalLoadedItems != -1 private val isNothingToLoadNeeded: Boolean get() = adapter?.itemCount == totalLoadedItems && !alreadyCalledOnNoMore val layoutManager: RecyclerView.LayoutManager? get() = _layoutManager constructor(adapter: FastAdapter<*>, totalItems: Int) { this.adapter = adapter totalLoadedItems = totalItems } constructor(adapter: FastAdapter<*>) { this.adapter = adapter } override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) { super.onScrolled(recyclerView, dx, dy) if (!::_layoutManager.isInitialized) { this._layoutManager = recyclerView.layoutManager as LinearLayoutManager? ?: throw RuntimeException("A LayoutManager is required") } if (visibleThreshold == RecyclerView.NO_POSITION) { visibleThreshold = findLastVisibleItemPosition(recyclerView) - findFirstVisibleItemPosition(recyclerView) } visibleItemCount = recyclerView.childCount totalItemCount = _layoutManager.itemCount firstVisibleItem = findFirstVisibleItemPosition(recyclerView) totalItemCount = adapter?.itemCount ?: 0 if (isLoading) { if (totalItemCount > previousTotal) { isLoading = false previousTotal = totalItemCount } } if (!isLoading && _layoutManager.findFirstVisibleItemPosition() - visibleThreshold <= 0) { currentPage++ onLoadMore(currentPage) isLoading = true } else { if (isNothingToLoadFeatureEnabled && isNothingToLoadNeeded) { onNothingToLoad() alreadyCalledOnNoMore = true } } } private fun findLastVisibleItemPosition(recyclerView: RecyclerView): Int { val child = findOneVisibleChild(recyclerView.childCount - 1, -1, false, true) return if (child == null) RecyclerView.NO_POSITION else recyclerView.getChildAdapterPosition(child) } private fun findFirstVisibleItemPosition(recyclerView: RecyclerView): Int { val child = findOneVisibleChild(0, _layoutManager.childCount, false, true) return if (child == null) RecyclerView.NO_POSITION else recyclerView.getChildAdapterPosition(child) } /** * Load more data * * @param page page number, starts from 0 */ abstract fun onLoadMore(page: Int) /** * There's no more data to be loaded, you may want * to send a request to server for asking more data */ abstract fun onNothingToLoad() private fun findOneVisibleChild(fromIndex: Int, toIndex: Int, completelyVisible: Boolean, acceptPartiallyVisible: Boolean): View? { if (_layoutManager.canScrollVertically() != isOrientationHelperVertical || orientationHelper == null) { isOrientationHelperVertical = _layoutManager.canScrollVertically() orientationHelper = if (isOrientationHelperVertical) OrientationHelper.createVerticalHelper(_layoutManager) else OrientationHelper.createHorizontalHelper(_layoutManager) } val mOrientationHelper = this.orientationHelper ?: return null val start = mOrientationHelper.startAfterPadding val end = mOrientationHelper.endAfterPadding val next = if (toIndex > fromIndex) 1 else -1 var partiallyVisible: View? = null var i = fromIndex while (i != toIndex) { val child = _layoutManager.getChildAt(i) if (child != null) { val childStart = mOrientationHelper.getDecoratedStart(child) val childEnd = mOrientationHelper.getDecoratedEnd(child) if (childStart < end && childEnd > start) { if (completelyVisible) { if (childStart >= start && childEnd <= end) { return child } else if (acceptPartiallyVisible && partiallyVisible == null) { partiallyVisible = child } } else { return child } } } i += next } return partiallyVisible } /** * Reset page count */ fun resetPageCount() { this.resetPageCount(0) } /** * Reset page count to specified page * * @param page page number, starts from 0 */ fun resetPageCount(page: Int) { this.previousTotal = 0 this.isLoading = true this.currentPage = page this.onLoadMore(this.currentPage) } }
apache-2.0
535e1626d6d5d5965af46f6e9887d0df
34.88024
117
0.633344
5.502296
false
false
false
false
cdietze/klay
tripleklay/src/main/kotlin/tripleklay/util/JsonUtil.kt
1
4382
package tripleklay.util import klay.core.Json import klay.core.Platform /** * Facilities for parsing JSON data */ object JsonUtil { /** * @return the Enum whose name corresponds to string for the given key, or `null` if the key doesn't exist. */ inline fun <reified T : Enum<T>> getEnum(json: Json.Object, key: String): T? { return getString(json, key)?.let { enumValueOf<T>(it) } } /** * @return the Enum whose name corresponds to string for the given key. * @throws RuntimeException if the key doesn't exist. */ inline fun <reified T : Enum<T>> requireEnum(json: Json.Object, key: String): T { return enumValueOf(requireString(json, key)) } /** * @return the boolean value at the given key, or `defaultVal` if the key doesn't exist. */ fun getBoolean(json: Json.Object, key: String): Boolean? = json.getBoolean(key) /** * @return the boolean value at the given key. * @throws RuntimeException if the key doesn't exist. */ fun requireBoolean(json: Json.Object, key: String): Boolean { requireKey(json, key) return json.getBoolean(key)!! } /** * @return the double value at the given key, or `null` if the key doesn't exist. */ fun getDouble(json: Json.Object, key: String): Double? = json.getDouble(key) /** * @return the double value at the given key. * @throws RuntimeException if the key doesn't exist. */ fun requireDouble(json: Json.Object, key: String): Double { requireKey(json, key) return json.getDouble(key)!! } /** * @return the float value at the given key, or `null` if the key doesn't exist. */ fun getFloat(json: Json.Object, key: String): Float? = json.getFloat(key) /** * @return the float value at the given key. * @throws RuntimeException if the key doesn't exist. */ fun requireFloat(json: Json.Object, key: String): Float { requireKey(json, key) return json.getFloat(key)!! } /** * @return the int value at the given key, or `null` if the key doesn't exist. */ fun getInt(json: Json.Object, key: String): Int? = json.getInt(key) /** * @return the int value at the given key. * @throws RuntimeException if the key doesn't exist. */ fun requireInt(json: Json.Object, key: String): Int { requireKey(json, key) return json.getInt(key)!! } /** * @return the String value at the given key, or `null` if the key doesn't exist. */ fun getString(json: Json.Object, key: String): String? { return json.getString(key) } /** * @return the String value at the given key. * @throws RuntimeException if the key doesn't exist. */ fun requireString(json: Json.Object, key: String): String { requireKey(json, key) return json.getString(key)!! } /** * @return the Json.Object value at the given key, or `null` if the key doesn't exist. */ fun getObject(json: Json.Object, key: String): Json.Object? = json.getObject(key) /** * @return the Json.Object at the given key. * @throws RuntimeException if the key doesn't exist. */ fun requireObject(json: Json.Object, key: String): Json.Object { requireKey(json, key) return json.getObject(key)!! } /** * @return the Json.Object value at the given key, or `null` if the key doesn't exist. */ fun getArray(json: Json.Object, key: String): Json.Array? = json.getArray(key) /** * @return the Json.Array at the given key. * @throws RuntimeException if the key doesn't exist. */ fun requireArray(json: Json.Object, key: String): Json.Array { requireKey(json, key) return json.getArray(key)!! } /** * @return a String representation of the given Json */ fun toString(plat: Platform, json: Json.Object, verbose: Boolean): String { val writer = plat.json.newWriter().useVerboseFormat(verbose) writer.`object`() json.write(writer) writer.end() return writer.write() } private fun requireKey(json: Json.Object, key: String) { if (!json.containsKey(key)) { throw RuntimeException("Missing required key [name=$key]") } } }
apache-2.0
bbd6fa4e43dd480e312df1e14fd78de3
29.859155
111
0.613419
3.930045
false
false
false
false
Gark/bassblog_kotlin
app/src/main/java/pixel/kotlin/bassblog/network/NetworkService.kt
1
2095
package pixel.kotlin.bassblog.network import android.app.IntentService import android.content.Context import android.content.Intent import android.support.v4.os.ResultReceiver import android.util.Log import pixel.kotlin.bassblog.BuildConfig import java.io.IOException import java.text.SimpleDateFormat import java.util.* open class NetworkService : IntentService(NetworkService::class.java.name) { override fun onHandleIntent(intent: Intent?) { if (intent == null) return val helper = NetworkHelper() val receiver: ResultReceiver? = intent.getParcelableExtra(RECEIVER) val count = intent.getIntExtra(COUNT, DEFAULT_COUNT) val endTimeLong = intent.getLongExtra(END_TIME, DEFAULT_TIME) val startTimeLong = intent.getLongExtra(START_TIME, DEFAULT_TIME) try { helper.requestMixes(count, startTimeLong, endTimeLong) receiver?.send(IDLE, null) } catch (exp: IOException) { if (BuildConfig.DEBUG) Log.e(TAG, "network request error", exp) receiver?.send(IDLE, null) } } companion object { val DEFAULT_TIME = 0L val FORMATTER = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ", Locale.ENGLISH) protected val START_TIME = "START_TIME" protected val END_TIME = "END_TIME" protected val COUNT = "COUNT" protected val RECEIVER = "RECEIVER" val LOADING = 10 val IDLE = 11 init { FORMATTER.timeZone = TimeZone.getTimeZone("UTC") } private val DEFAULT_COUNT = 20 private val TAG = NetworkService::class.java.name fun start(context: Context, receiver: ResultReceiver, startTime: Long? = null, endTime: Long? = null, count: Int = DEFAULT_COUNT) { val intent = Intent(context, NetworkService::class.java) intent.putExtra(START_TIME, startTime) intent.putExtra(END_TIME, endTime) intent.putExtra(COUNT, count) intent.putExtra(RECEIVER, receiver) context.startService(intent) } } }
agpl-3.0
d0f1e321e7338a6e716f00da69c56c26
33.933333
139
0.657279
4.355509
false
false
false
false
tommyli/nem12-manager
fenergy-service/src/main/kotlin/co/firefire/fenergy/nem12/domain/IntervalQuality.kt
1
1483
// Tommy Li ([email protected]), 2017-03-10 package co.firefire.fenergy.nem12.domain import java.time.LocalDateTime import javax.persistence.Embeddable import javax.persistence.EnumType import javax.persistence.Enumerated /** * Order of declaration matters here, it determines which intervalQuality takes precedense */ enum class Quality { V, N, E, S, F, A } @Embeddable data class IntervalQuality( @Enumerated(EnumType.STRING) val quality: Quality = Quality.A ) { constructor(quality: Quality, method: String?, reasonCode: String?, reasonDescription: String?) : this(quality) { this.method = method this.reasonCode = reasonCode this.reasonDescription = reasonDescription } var method: String? = null var reasonCode: String? = null var reasonDescription: String? = null override fun toString(): String { return "IntervalQuality(intervalQuality=$quality)" } } data class TimestampedQuality(val quality: Quality, val timestamp: LocalDateTime) : Comparable<TimestampedQuality> { override fun compareTo(other: TimestampedQuality): Int { return if (quality.compareTo(other.quality) == 0) { if (timestamp < other.timestamp) { -1 } else if (timestamp == other.timestamp) { 0 } else { 1 } } else { quality.compareTo(other.quality) } } }
apache-2.0
e1f1a97a8ae9d4e4920f4601ef97a5e1
24.568966
117
0.63857
4.336257
false
false
false
false
Seancheey/Ark-Sonah
src/com/seancheey/game/model/Node.kt
1
3181
package com.seancheey.game.model import com.seancheey.game.battlefield.Battlefield /** * Created by Seancheey on 30/05/2017. * GitHub: https://github.com/Seancheey */ interface Node : Model { companion object { fun correctArcAngle(arc: Double): Double { if (arc > Math.PI * 2) { return correctArcAngle(arc - 2 * Math.PI) } else if (arc < 0) { return correctArcAngle(arc + 2 * Math.PI) } return arc } fun minAngleDifference(arc1: Double, arc2: Double): Double { val diff0 = arc1 - arc2 val diff1 = diff0 + 2 * Math.PI val diff2 = diff0 - 2 * Math.PI val min = minOf(Math.abs(diff0), Math.abs(diff1), Math.abs(diff2)) when (min) { Math.abs(diff0) -> return diff0 Math.abs(diff1) -> return diff1 Math.abs(diff2) -> return diff2 else -> return diff0 } } } /** * center position x */ var x: Double /** * center position y */ var y: Double /** * position of the node's four edge points */ val leftX: Double get() = x - width / 2 val upperY: Double get() = y - height / 2 val rightX: Double get() = x + width / 2 val lowerY: Double get() = y + height / 2 /** * orientation in arc, 0 <= orientation <= 2*PI * node with 0 arc orientation is heading towards right (positive x-axis) */ var orientation: Double /** * orientation in degree */ val degreeOrientation: Double get() = orientation * 180 / Math.PI /** * peer mutableNodes that this node may affect */ val peers: ArrayList<Node> /** * children node list */ val children: ArrayList<Node> /** * children for observing only * prevent concurrency issue */ val immutableChildren: List<Node> get() = children.map { it } /** * the battlefield this node is at */ var field: Battlefield /** * set it to true to let gameDirector to remove this node */ var requestDeletion: Boolean /** * set by GameInspector, used for handling any possible event when focused */ var focusedByPlayer: Boolean /** * update function is called each frame to make node perform actions */ fun update() { children.removeAll(children.filter { it.requestDeletion }) actionTree.executeAll(this) children.forEach { it.update() } } fun containsPoint(pointX: Double, pointY: Double): Boolean { if (pointX < leftX || pointY < upperY || pointX > rightX || pointY > lowerY) return false return true } fun distanceTo(pointX: Double, pointY: Double): Double { val dx = pointX - x val dy = pointY - y return Math.sqrt(dx * dx + dy * dy) } fun correctOrientation() { orientation = correctArcAngle(orientation) } fun updateFocusedStatus() {} }
mit
7b9c4a0dbdf5b3d8e93b369d6c6d920d
25.516667
97
0.541025
4.202114
false
false
false
false
android/location-samples
ActivityRecognition/app/src/main/java/com/google/android/gms/location/sample/activityrecognition/data/db/ActivityTransitionRecord.kt
1
3033
/* * Copyright 2022 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 * * 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.android.gms.location.sample.activityrecognition.data.db import android.os.SystemClock import androidx.room.Entity import androidx.room.PrimaryKey import androidx.room.TypeConverters import com.google.android.gms.location.ActivityTransition import com.google.android.gms.location.ActivityTransitionEvent import com.google.android.gms.location.DetectedActivity import java.time.Duration import java.time.Instant /** * Entity representing an activity transition event. */ @Entity @TypeConverters(TimestampConverter::class) data class ActivityTransitionRecord( @PrimaryKey(autoGenerate = true) val id: Int = 0, val activityType: DetectedActivityType, val transitionType: DetectedTransitionType, val timestamp: Instant ) /** * Enumerated form of Play Services [DetectedActivity] types. Note: some types are not supported by * activity transitions API, only supported types are enumerated here. */ enum class DetectedActivityType(val type: Int) { IN_VEHICLE(DetectedActivity.IN_VEHICLE), ON_BICYCLE(DetectedActivity.ON_BICYCLE), ON_FOOT(DetectedActivity.ON_FOOT), RUNNING(DetectedActivity.RUNNING), STILL(DetectedActivity.STILL), WALKING(DetectedActivity.WALKING); companion object { fun forType(type: Int): DetectedActivityType { return values().first { it.type == type } } } } /** * Enumerated form of Play Services [ActivityTransition] types. */ enum class DetectedTransitionType(private val type: Int) { ENTER(ActivityTransition.ACTIVITY_TRANSITION_ENTER), EXIT(ActivityTransition.ACTIVITY_TRANSITION_EXIT); companion object { fun forType(type: Int): DetectedTransitionType { return values().first { it.type == type } } } } /** * Utility to convert a Play Services [ActivityTransitionEvent] to a database entity type. */ fun ActivityTransitionEvent.asRecord() = ActivityTransitionRecord( activityType = DetectedActivityType.forType(activityType), transitionType = DetectedTransitionType.forType(transitionType), timestamp = elapsedRealTimeNanosToInstant(elapsedRealTimeNanos) ) private fun elapsedRealTimeNanosToInstant(elapsedRealTimeNanos: Long): Instant { val currentElapsedRealtimeNanos = SystemClock.elapsedRealtimeNanos() val currentInstant = Instant.now() return currentInstant - Duration.ofNanos(currentElapsedRealtimeNanos - elapsedRealTimeNanos) }
apache-2.0
3bec297d5e27cb1ed3238a43122431ce
33.862069
99
0.759314
4.351506
false
false
false
false
ben-manes/gradle-versions-plugin
gradle-versions-plugin/src/main/kotlin/com/github/benmanes/gradle/versions/updates/gradle/GradleUpdateResult.kt
1
2804
package com.github.benmanes.gradle.versions.updates.gradle import com.github.benmanes.gradle.versions.updates.gradle.GradleUpdateChecker.ReleaseStatus import org.gradle.util.GradleVersion /** * Holder class for gradle update results of a specific release channel (or the running version). * Used for reporting & serialization to JSON/XML. */ class GradleUpdateResult( enabled: Boolean = false, running: ReleaseStatus.Available? = null, release: ReleaseStatus? = null, ) : Comparable<GradleUpdateResult> { /** * The version available on the release channel represented by this object. */ var version: String /** * Indicates whether the [version] is an update with respect to the currently running gradle * version. */ var isUpdateAvailable: Boolean /** * Indicates whether the check for Gradle updates on this release channel failed. */ var isFailure: Boolean /** * An explanatory field on how to interpret the results. Useful when [version] is not set to a * valid value. */ var reason: String init { if (!enabled) { version = "" isUpdateAvailable = false isFailure = false reason = "update check disabled" } else if (release is ReleaseStatus.Available) { version = release.gradleVersion.version isUpdateAvailable = release.gradleVersion > running!!.gradleVersion isFailure = false reason = "" // empty string so the field is serialized } else if (release is ReleaseStatus.Unavailable) { version = "" // empty string so the field is serialized isUpdateAvailable = false isFailure = false reason = "update check succeeded: no release available" } else if (release is ReleaseStatus.Failure) { version = "" // empty string so the field is serialized isUpdateAvailable = false isFailure = true reason = release.reason } else { throw IllegalStateException( "ReleaseStatus subtype [" + release!!.javaClass + "] not yet implemented" ) } } /** * Compares two instances of [GradleUpdateResult]. * * @return an integer as specified by [Comparable.compareTo] * @throws IllegalArgumentException when one of the [GradleUpdateResult]s does not represent * a valid [GradleVersion]. This may be the case when a [GradleUpdateResult] * represents a failure. */ override fun compareTo(other: GradleUpdateResult): Int { return comparator.compare(this, other) } companion object { /** * Comparator that compares two instances of [GradleUpdateResult] by comparing the * [GradleVersion] they represent */ private val comparator = Comparator.comparing { gradleUpdateResult: GradleUpdateResult -> GradleVersion.version(gradleUpdateResult.version) } } }
apache-2.0
7560f1b4c946b37c1b52e446463f8bfd
31.229885
97
0.696862
4.809605
false
false
false
false
JetBrains/intellij-community
plugins/kotlin/code-insight/intentions-k2/src/org/jetbrains/kotlin/idea/k2/codeinsight/intentions/AddNamesToFollowingArgumentsIntention.kt
1
3226
// 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.k2.codeinsight.intentions import com.intellij.codeInsight.intention.LowPriorityAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.SmartPsiElementPointer import org.jetbrains.kotlin.analysis.api.KtAnalysisSession import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.codeinsight.api.applicable.intentions.AbstractKotlinApplicableIntentionWithContext import org.jetbrains.kotlin.idea.codeinsight.utils.dereferenceValidKeys import org.jetbrains.kotlin.idea.codeinsights.impl.base.applicators.ApplicabilityRanges import org.jetbrains.kotlin.idea.codeinsights.impl.base.intentions.AddArgumentNamesUtils.addArgumentNames import org.jetbrains.kotlin.idea.codeinsights.impl.base.intentions.AddArgumentNamesUtils.associateArgumentNamesStartingAt import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.psi.KtCallElement import org.jetbrains.kotlin.psi.KtLambdaArgument import org.jetbrains.kotlin.psi.KtValueArgument import org.jetbrains.kotlin.psi.KtValueArgumentList internal class AddNamesToFollowingArgumentsIntention : AbstractKotlinApplicableIntentionWithContext<KtValueArgument, AddNamesToFollowingArgumentsIntention.Context>(KtValueArgument::class), LowPriorityAction { class Context(val argumentNames: Map<SmartPsiElementPointer<KtValueArgument>, Name>) override fun getFamilyName(): String = KotlinBundle.message("add.names.to.this.argument.and.following.arguments") override fun getActionName(element: KtValueArgument, context: Context): String = familyName override fun getApplicabilityRange() = ApplicabilityRanges.VALUE_ARGUMENT_EXCLUDING_LAMBDA override fun isApplicableByPsi(element: KtValueArgument): Boolean { // Not applicable when lambda is trailing lambda after argument list (e.g., `run { }`); element is a KtLambdaArgument. // May be applicable when lambda is inside an argument list (e.g., `run({ })`); element is a KtValueArgument in this case. if (element.isNamed() || element is KtLambdaArgument) { return false } val argumentList = element.parent as? KtValueArgumentList ?: return false // Shadowed by `AddNamesToCallArgumentsIntention` if (argumentList.arguments.firstOrNull() == element) return false // Shadowed by `AddNameToArgumentIntention` if (argumentList.arguments.lastOrNull { !it.isNamed() } == element) return false return true } context(KtAnalysisSession) override fun prepareContext(element: KtValueArgument): Context? { val argumentList = element.parent as? KtValueArgumentList ?: return null val call = argumentList.parent as? KtCallElement ?: return null return associateArgumentNamesStartingAt(call, element)?.let { Context(it) } } override fun apply(element: KtValueArgument, context: Context, project: Project, editor: Editor?) = addArgumentNames(context.argumentNames.dereferenceValidKeys()) }
apache-2.0
c18e2c7e279e496273dade6a02841e62
55.614035
158
0.787663
4.910198
false
false
false
false
customerly/Customerly-Android-SDK
customerly-android-sdk/src/main/java/io/customerly/utils/ClyForegroundAppChecker.kt
1
3248
package io.customerly.utils /* * Copyright (C) 2017 Customerly * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import android.app.Activity import android.app.Application import android.content.Context import android.os.Bundle import android.os.Handler import android.os.Looper import io.customerly.utils.ggkext.weak import java.lang.ref.WeakReference /** * Created by Gianni on 25/03/17. */ @Suppress("MemberVisibilityCanPrivate", "unused") internal abstract class ForegroundAppChecker : Application.ActivityLifecycleCallbacks { private var lastDisplayedActivity : WeakReference<Activity>? = null private var pausedApplicationContext : WeakReference<Context>? = null private var foreground = false private val checkBackground = Runnable { this.pausedApplicationContext?.get()?.let { applicationContext -> if (this.foreground) { this.foreground = false this.doOnAppGoBackground(applicationContext = applicationContext) } } } internal val isInBackground : Boolean get() = !this.foreground internal fun getLastDisplayedActivity() : Activity? = this.lastDisplayedActivity?.get() final override fun onActivityResumed(activity: Activity) { this.lastDisplayedActivity = activity.weak() this.pausedApplicationContext = null val wasBackground = !this.foreground this.foreground = true Handler(Looper.getMainLooper()).removeCallbacks(this.checkBackground) this.doOnActivityResumed(activity, wasBackground) } final override fun onActivityPaused(activity: Activity) { this.pausedApplicationContext = activity.applicationContext.weak() val h = Handler(Looper.getMainLooper()) h.removeCallbacks(this.checkBackground) h.postDelayed(this.checkBackground, 500) this.doOnActivityPaused(activity) } final override fun onActivityDestroyed(activity: Activity) { if(this.lastDisplayedActivity?.get() == activity) { this.lastDisplayedActivity = null } this.doOnActivityDestroyed(activity = activity) } override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {} override fun onActivityStarted(activity: Activity) {} override fun onActivityStopped(activity: Activity) {} override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle?) {} protected abstract fun doOnAppGoBackground(applicationContext : Context) protected abstract fun doOnActivityResumed(activity: Activity, fromBackground: Boolean) protected open fun doOnActivityDestroyed(activity: Activity) {} protected open fun doOnActivityPaused(activity: Activity) {} }
apache-2.0
e7a624c9e2abbb6b678de76414b98819
39.098765
91
0.732451
4.943683
false
false
false
false
allotria/intellij-community
platform/lang-api/src/com/intellij/psi/util/PartiallyKnownString.kt
2
12874
// 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.psi.util import com.intellij.openapi.diagnostic.Attachment import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.util.TextRange import com.intellij.psi.ContributedReferenceHost import com.intellij.psi.ElementManipulators import com.intellij.psi.PsiElement import com.intellij.psi.PsiLanguageInjectionHost import com.intellij.refactoring.suggested.startOffset import com.intellij.util.SmartList import com.intellij.util.castSafelyTo import com.intellij.util.containers.headTailOrNull import org.jetbrains.annotations.ApiStatus /** * Represents string which value is only partially known because of some variables concatenated with or interpolated into the string. * * For UAST languages it could be obtained from `UStringConcatenationsFacade.asPartiallyKnownString`. * * The common use case is a search for a place in partially known content to inject a reference. */ @ApiStatus.Experimental class PartiallyKnownString(val segments: List<StringEntry>) { val valueIfKnown: String? get() { (segments.singleOrNull() as? StringEntry.Known)?.let { return it.value } val stringBuffer = StringBuffer() for (segment in segments) { when (segment) { is StringEntry.Known -> stringBuffer.append(segment.value) is StringEntry.Unknown -> return null } } return stringBuffer.toString() } val concatenationOfKnown: String get() { (segments.singleOrNull() as? StringEntry.Known)?.let { return it.value } val stringBuffer = StringBuffer() for (segment in segments) { if (segment is StringEntry.Known) stringBuffer.append(segment.value) } return stringBuffer.toString() } override fun toString(): String = segments.joinToString { segment -> when (segment) { is StringEntry.Known -> segment.value is StringEntry.Unknown -> "<???>" } } constructor(single: StringEntry) : this(listOf(single)) constructor(string: String, sourcePsi: PsiElement?, textRange: TextRange) : this( StringEntry.Known(string, sourcePsi, textRange)) constructor(string: String) : this(string, null, TextRange.EMPTY_RANGE) @JvmOverloads fun findIndexOfInKnown(pattern: String, startFrom: Int = 0): Int { var accumulated = 0 for (segment in segments) { when (segment) { is StringEntry.Known -> { val i = segment.value.indexOf(pattern, startFrom - accumulated) if (i >= 0) return accumulated + i accumulated += segment.value.length } is StringEntry.Unknown -> { } } } return -1 } private fun buildSegmentWithMappedRange(value: String, sourcePsi: PsiElement?, rangeInPks: TextRange): StringEntry.Known = StringEntry.Known( value, sourcePsi, sourcePsi.castSafelyTo<PsiLanguageInjectionHost>()?.let { host -> mapRangeToHostRange(host, getRangeInHost(host) ?: ElementManipulators.getValueTextRange(host), rangeInPks) } ?: rangeInPks ) fun splitAtInKnown(splitAt: Int): Pair<PartiallyKnownString, PartiallyKnownString> { var accumulated = 0 val left = SmartList<StringEntry>() for ((i, segment) in segments.withIndex()) { when (segment) { is StringEntry.Known -> { if (accumulated + segment.value.length < splitAt) { accumulated += segment.value.length left.add(segment) } else { val leftPart = segment.value.substring(0, splitAt - accumulated) val rightPart = segment.value.substring(splitAt - accumulated) left.add(buildSegmentWithMappedRange(leftPart, segment.sourcePsi, TextRange.from(0, leftPart.length))) return PartiallyKnownString(left) to PartiallyKnownString( ArrayList<StringEntry>(segments.lastIndex - i + 1).apply { if (rightPart.isNotEmpty()) add(buildSegmentWithMappedRange(rightPart, segment.sourcePsi, TextRange.from(leftPart.length, rightPart.length))) addAll(segments.subList(i + 1, segments.size)) } ) } } is StringEntry.Unknown -> { left.add(segment) } } } return this to empty } fun split(pattern: String, escaperFactory: (CharSequence, String) -> SplitEscaper = { _, _ -> SplitEscaper.AcceptAll }) : List<PartiallyKnownString> { tailrec fun collectPaths(result: MutableList<PartiallyKnownString>, pending: MutableList<StringEntry>, segments: List<StringEntry>): MutableList<PartiallyKnownString> { val (head, tail) = segments.headTailOrNull() ?: return result.apply { add(PartiallyKnownString(pending)) } fun rangeForSubElement(partRange: TextRange): TextRange = head.rangeAlignedToHost ?.let { (host, hostRange) -> mapRangeToHostRange(host, hostRange, partRange)?.shiftLeft(head.sourcePsi!!.startOffset - host.startOffset) } ?: partRange.shiftRight(head.range.startOffset) when (head) { is StringEntry.Unknown -> return collectPaths(result, pending.apply { add(head) }, tail) is StringEntry.Known -> { val value = head.value val stringParts = splitToTextRanges(value, pattern, escaperFactory).toList() if (stringParts.size == 1) { return collectPaths(result, pending.apply { add(head) }, tail) } else { return collectPaths( result.apply { add(PartiallyKnownString( pending.apply { add(StringEntry.Known(stringParts.first().substring(value), head.sourcePsi, rangeForSubElement(stringParts.first()))) })) addAll(stringParts.subList(1, stringParts.size - 1).map { PartiallyKnownString(it.substring(value), head.sourcePsi, rangeForSubElement(it)) }) }, mutableListOf(StringEntry.Known(stringParts.last().substring(value), head.sourcePsi, rangeForSubElement(stringParts.last()))), tail ) } } } } return collectPaths(SmartList(), mutableListOf(), segments) } fun mapRangeToHostRange(host: PsiElement, rangeInPks: TextRange): TextRange? = mapRangeToHostRange(host, ElementManipulators.getValueTextRange(host), rangeInPks) /** * @return the range in the given [host] (encoder-aware) that corresponds to the [rangeInPks] in the [valueIfKnown] * @param rangeInHost - range in the [host] if the only the part of the [host] should be considered. * useful if [host] corresponds to multiple [PartiallyKnownString] * * NOTE: currently supports only single-segment [rangeInPks] */ fun mapRangeToHostRange(host: PsiElement, rangeInHost: TextRange, rangeInPks: TextRange): TextRange? { fun getHostRangeEscapeAware(segmentRange: TextRange, inSegmentStart: Int, inSegmentEnd: Int): TextRange { if (host is PsiLanguageInjectionHost) { val escaper = host.createLiteralTextEscaper() val decode = escaper.decode(segmentRange, StringBuilder()) if (decode) { val start = escaper.getOffsetInHost(inSegmentStart, segmentRange) val end = escaper.getOffsetInHost(inSegmentEnd, segmentRange) if (start != -1 && end != -1 && start <= end) return TextRange(start, end) else { logger<PartiallyKnownString>().error( "decoding of ${segmentRange} failed for $host : [$start, $end] inSegment = [$inSegmentStart, $inSegmentEnd]", Attachment("host:", host.text ?: "<null>"), Attachment("file:", host.containingFile?.text ?: "<null>") ) return TextRange(segmentRange.startOffset + inSegmentStart, segmentRange.startOffset + inSegmentEnd) } } } return TextRange(segmentRange.startOffset + inSegmentStart, segmentRange.startOffset + inSegmentEnd) } var accumulated = 0 for (segment in segments) { if (segment !is StringEntry.Known) continue val (segmentHost, segmentRangeInHost) = segment.rangeAlignedToHost ?: continue if (segmentHost != host || !rangeInHost.contains(segmentRangeInHost)) continue // we don't support partial intersections val segmentEnd = accumulated + segment.value.length // assume that all content fits into one segment if (rangeInPks.startOffset >= accumulated && rangeInPks.endOffset <= segmentEnd) { val inSegmentStart = rangeInPks.startOffset - accumulated val inSegmentEnd = rangeInPks.endOffset - accumulated return getHostRangeEscapeAware(segmentRangeInHost, inSegmentStart, inSegmentEnd) } accumulated = segmentEnd } return null } /** * @return the range in the [valueIfKnown] that corresponds to given [host] */ fun getRangeOfTheHostContent(host: PsiElement): TextRange? { var accumulated = 0 var start = 0 var end = 0 var found = false for (segment in segments) { if (segment !is StringEntry.Known) continue if (segment.host == host) { if (!found) { found = true start = accumulated } end = accumulated + segment.value.length } accumulated += segment.value.length } if (found) return TextRange.from(start, end) else return null } /** * @return the cumulative range in the [originalHost] used by this [PartiallyKnownString] */ fun getRangeInHost(originalHost: PsiElement): TextRange? { val ranges = segments.asSequence().mapNotNull { it.rangeAlignedToHost?.takeIf { it.first == originalHost } }.map { it.second }.toList() if (ranges.isEmpty()) return null return ranges.reduce(TextRange::union) } companion object { val empty = PartiallyKnownString(emptyList()) } } @ApiStatus.Experimental sealed class StringEntry { abstract val sourcePsi: PsiElement? // maybe it should be PsiLanguageInjectionHost and only for `Known` values /** * A range in the [sourcePsi] that corresponds to the content of this segment */ abstract val range: TextRange class Known(val value: String, override val sourcePsi: PsiElement?, override val range: TextRange) : StringEntry() { override fun toString(): String = "StringEntry.Known('$value' at $range in $sourcePsi)" } class Unknown(override val sourcePsi: PsiElement?, override val range: TextRange) : StringEntry() { override fun toString(): String = "StringEntry.Unknown(at $range in $sourcePsi)" } val host: PsiElement? get() = sourcePsi.takeIf { it.isSuitableHostClass() } ?: sourcePsi?.parent.takeIf { it.isSuitableHostClass() } val rangeAlignedToHost: Pair<PsiElement, TextRange>? get() { val entry = this val sourcePsi = entry.sourcePsi ?: return null if (sourcePsi.isSuitableHostClass()) return sourcePsi to entry.range val parent = sourcePsi.parent if (parent is PsiLanguageInjectionHost) { // Kotlin interpolated string, TODO: encapsulate this logic to range retrieval return parent to entry.range.shiftRight(sourcePsi.startOffsetInParent) } return null } private fun PsiElement?.isSuitableHostClass(): Boolean = when(this) { // this is primarily to workaround injections into YAMLKeyValue (which doesn't implement {@code PsiLanguageInjectionHost}) is ContributedReferenceHost, is PsiLanguageInjectionHost -> true else -> false } } @ApiStatus.Experimental fun splitToTextRanges(charSequence: CharSequence, pattern: String, escaperFactory: (CharSequence, String) -> SplitEscaper = { _, _ -> SplitEscaper.AcceptAll }): Sequence<TextRange> { var lastMatch = 0 var lastSplit = 0 val escaper = escaperFactory(charSequence, pattern) return sequence { while (true) { val start = charSequence.indexOf(pattern, lastMatch) if (start == -1) { yield(TextRange(lastSplit, charSequence.length)) return@sequence } lastMatch = start + pattern.length if (escaper.filter(lastSplit, start)) { yield(TextRange(lastSplit, start)) lastSplit = lastMatch } } } } @ApiStatus.Experimental interface SplitEscaper { fun filter(lastSplit: Int, currentPosition: Int): Boolean object AcceptAll : SplitEscaper { override fun filter(lastSplit: Int, currentPosition: Int): Boolean = true } }
apache-2.0
fe70f9efbcc5b1ee7d36824c95005c7e
36.103746
140
0.659624
4.541093
false
false
false
false
allotria/intellij-community
xml/impl/src/com/intellij/codeInsight/daemon/impl/tagTreeHighlighting/XmlTagTreeHighlightingConfigurable.kt
3
3053
/* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.codeInsight.daemon.impl.tagTreeHighlighting import com.intellij.application.options.editor.WebEditorOptions import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.fileEditor.TextEditor import com.intellij.openapi.options.UiDslConfigurable import com.intellij.openapi.project.ProjectManager import com.intellij.ui.layout.* import com.intellij.xml.XmlBundle import com.intellij.xml.breadcrumbs.BreadcrumbsPanel import javax.swing.JSpinner import javax.swing.SpinnerNumberModel class XmlTagTreeHighlightingConfigurable : UiDslConfigurable.Simple() { override fun RowBuilder.createComponentRow() { val options = WebEditorOptions.getInstance() row { val enable = checkBox(XmlBundle.message("settings.enable.html.xml.tag.tree.highlighting"), options::isTagTreeHighlightingEnabled, options::setTagTreeHighlightingEnabled) .onApply { clearTagTreeHighlighting() } val spinnerGroupName = "xml.tag.highlight.spinner" row(XmlBundle.message("settings.levels.to.highlight")) { spinner({ options.tagTreeHighlightingLevelCount }, { options.tagTreeHighlightingLevelCount = it }, 1, 50, 1) .onApply { clearTagTreeHighlighting() } .sizeGroup(spinnerGroupName) .enableIf(enable.selected) } row(XmlBundle.message("settings.opacity")) { component(JSpinner()) .applyToComponent { model = SpinnerNumberModel(0.0, 0.0, 1.0, 0.05) } .withBinding({ ((it.value as Double) * 100).toInt() }, { it, value -> it.value = value * 0.01 }, PropertyBinding(options::getTagTreeHighlightingOpacity, options::setTagTreeHighlightingOpacity)) .onApply { clearTagTreeHighlighting() } .sizeGroup(spinnerGroupName) .enableIf(enable.selected) largeGapAfter() } } } companion object { private fun clearTagTreeHighlighting() { for (project in ProjectManager.getInstance().openProjects) { for (fileEditor in FileEditorManager.getInstance(project).allEditors) { if (fileEditor is TextEditor) { val editor = fileEditor.editor XmlTagTreeHighlightingPass.clearHighlightingAndLineMarkers(editor, project) val breadcrumbs = BreadcrumbsPanel.getBreadcrumbsComponent(editor) breadcrumbs?.queueUpdate() } } } } } }
apache-2.0
9cbd066961ec32e5e191648220a0a66a
40.821918
119
0.708156
4.740683
false
false
false
false
DmytroTroynikov/aemtools
aem-intellij-core/src/main/kotlin/com/aemtools/analysis/htl/callchain/typedescriptor/java/MapJavaTypeDescriptor.kt
1
1431
package com.aemtools.analysis.htl.callchain.typedescriptor.java import com.aemtools.analysis.htl.callchain.typedescriptor.base.MapTypeDescriptor import com.aemtools.analysis.htl.callchain.typedescriptor.base.TypeDescriptor import com.aemtools.lang.java.JavaSearch import com.intellij.psi.PsiClass import com.intellij.psi.PsiMember import com.intellij.psi.impl.source.PsiClassReferenceType /** * @author Dmytro Troynikov */ class MapJavaTypeDescriptor(psiClass: PsiClass, psiMember: PsiMember?, override val originalType: PsiClassReferenceType? = null) : JavaPsiClassTypeDescriptor(psiClass, psiMember, originalType), MapTypeDescriptor { override fun keyType(): TypeDescriptor { if (originalType == null) { return TypeDescriptor.empty() } val keyParam = originalType.parameters[0].canonicalText val psiClass = JavaSearch.findClass(keyParam, psiClass.project) ?: return TypeDescriptor.empty() return JavaPsiClassTypeDescriptor.create(psiClass, null, null) } override fun valueType(): TypeDescriptor { if (originalType == null) { return TypeDescriptor.empty() } val valueParam = originalType.parameters[1].canonicalText val psiClass = JavaSearch.findClass(valueParam, psiClass.project) ?: return TypeDescriptor.empty() return JavaPsiClassTypeDescriptor.create(psiClass, null, null) } }
gpl-3.0
7b6e397c59215fef720714c882f1fc9b
32.27907
87
0.737247
4.818182
false
false
false
false
smmribeiro/intellij-community
platform/lang-impl/src/com/intellij/ide/bookmark/ui/GroupInputValidator.kt
9
1616
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ide.bookmark.ui import com.intellij.ide.bookmark.BookmarkBundle.message import com.intellij.ide.bookmark.BookmarkGroup import com.intellij.ide.bookmark.BookmarksManager import com.intellij.openapi.Disposable import com.intellij.openapi.ui.ComponentValidator import com.intellij.openapi.ui.InputValidatorEx import com.intellij.openapi.ui.ValidationInfo import java.util.function.Supplier import javax.swing.JComponent internal class GroupInputValidator(val manager: BookmarksManager, val groups: Collection<BookmarkGroup>) : InputValidatorEx { constructor(manager: BookmarksManager, group: BookmarkGroup) : this(manager, listOf(group)) constructor(manager: BookmarksManager) : this(manager, emptySet()) override fun getErrorText(name: String?) = when { name.isNullOrBlank() -> "" manager.getGroup(name.trim()).let { it == null || groups.contains(it) } -> null else -> message("dialog.name.exists.error") } internal fun findValidName(name: String): String { val initial = name.trim() if (checkInput(initial)) return initial for (index in 1..99) { val indexed = "$initial ($index)" if (checkInput(indexed)) return indexed } return initial } internal fun install(parent: Disposable, component: JComponent, text: () -> String?) = ComponentValidator(parent) .withValidator(Supplier { getErrorText(text())?.let { ValidationInfo(it, component) } }) .installOn(component) }
apache-2.0
d8c9ed6d295db2f7c7ed1e1eaa991b2b
42.675676
158
0.751856
4.164948
false
false
false
false
jotomo/AndroidAPS
app/src/main/java/info/nightscout/androidaps/setupwizard/SWDefinition.kt
1
21167
package info.nightscout.androidaps.setupwizard import android.Manifest import android.content.Context import androidx.appcompat.app.AppCompatActivity import dagger.android.HasAndroidInjector import info.nightscout.androidaps.Config import info.nightscout.androidaps.Constants import info.nightscout.androidaps.R import info.nightscout.androidaps.dialogs.ProfileSwitchDialog import info.nightscout.androidaps.events.EventPumpStatusChanged import info.nightscout.androidaps.interfaces.ActivePluginProvider import info.nightscout.androidaps.interfaces.CommandQueueProvider import info.nightscout.androidaps.interfaces.ImportExportPrefsInterface import info.nightscout.androidaps.interfaces.PluginType import info.nightscout.androidaps.interfaces.ProfileFunction import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin import info.nightscout.androidaps.plugins.constraints.objectives.ObjectivesFragment import info.nightscout.androidaps.plugins.constraints.objectives.ObjectivesPlugin import info.nightscout.androidaps.plugins.general.nsclient.NSClientPlugin import info.nightscout.androidaps.plugins.general.nsclient.events.EventNSClientStatus import info.nightscout.androidaps.plugins.general.nsclient.services.NSClientService import info.nightscout.androidaps.plugins.profile.local.LocalProfileFragment import info.nightscout.androidaps.plugins.profile.local.LocalProfilePlugin import info.nightscout.androidaps.plugins.profile.ns.NSProfileFragment import info.nightscout.androidaps.plugins.profile.ns.NSProfilePlugin import info.nightscout.androidaps.plugins.pump.common.events.EventRileyLinkDeviceStatusChange import info.nightscout.androidaps.plugins.pump.omnipod.OmnipodPumpPlugin import info.nightscout.androidaps.setupwizard.elements.* import info.nightscout.androidaps.setupwizard.events.EventSWUpdate import info.nightscout.androidaps.utils.AndroidPermission import info.nightscout.androidaps.utils.CryptoUtil import info.nightscout.androidaps.utils.extensions.isRunningTest import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.sharedPreferences.SP import java.util.* import javax.inject.Inject import javax.inject.Singleton @Singleton class SWDefinition @Inject constructor( injector: HasAndroidInjector, private val rxBus: RxBusWrapper, private val context: Context, resourceHelper: ResourceHelper, private val sp: SP, private val profileFunction: ProfileFunction, private val localProfilePlugin: LocalProfilePlugin, private val activePlugin: ActivePluginProvider, private val commandQueue: CommandQueueProvider, private val objectivesPlugin: ObjectivesPlugin, private val configBuilderPlugin: ConfigBuilderPlugin, private val loopPlugin: LoopPlugin, private val nsClientPlugin: NSClientPlugin, private val nsProfilePlugin: NSProfilePlugin, private val importExportPrefs: ImportExportPrefsInterface, private val androidPermission: AndroidPermission, private val cryptoUtil: CryptoUtil, private val config: Config ) { lateinit var activity: AppCompatActivity private val screens: MutableList<SWScreen> = ArrayList() fun getScreens(): List<SWScreen> { return screens } private fun add(newScreen: SWScreen?): SWDefinition { if (newScreen != null) screens.add(newScreen) return this } private val screenSetupWizard = SWScreen(injector, R.string.nav_setupwizard) .add(SWInfotext(injector) .label(R.string.welcometosetupwizard)) private val screenEula = SWScreen(injector, R.string.end_user_license_agreement) .skippable(false) .add(SWInfotext(injector) .label(R.string.end_user_license_agreement_text)) .add(SWBreak(injector)) .add(SWButton(injector) .text(R.string.end_user_license_agreement_i_understand) .visibility { !sp.getBoolean(R.string.key_i_understand, false) } .action { sp.putBoolean(R.string.key_i_understand, true) rxBus.send(EventSWUpdate(false)) }) .visibility { !sp.getBoolean(R.string.key_i_understand, false) } .validator { sp.getBoolean(R.string.key_i_understand, false) } private val screenUnits = SWScreen(injector, R.string.units) .skippable(false) .add(SWRadioButton(injector) .option(R.array.unitsArray, R.array.unitsValues) .preferenceId(R.string.key_units).label(R.string.units) .comment(R.string.setupwizard_units_prompt)) .validator { sp.contains(R.string.key_units) } private val displaySettings = SWScreen(injector, R.string.wear_display_settings) .skippable(false) .add(SWEditNumberWithUnits(injector, Constants.LOWMARK * Constants.MGDL_TO_MMOLL, 3.0, 8.0) .preferenceId(R.string.key_low_mark) .updateDelay(5) .label(R.string.low_mark) .comment(R.string.low_mark_comment)) .add(SWBreak(injector)) .add(SWEditNumberWithUnits(injector, Constants.HIGHMARK * Constants.MGDL_TO_MMOLL, 5.0, 20.0) .preferenceId(R.string.key_high_mark) .updateDelay(5) .label(R.string.high_mark) .comment(R.string.high_mark_comment)) private val screenPermissionBattery = SWScreen(injector, R.string.permission) .skippable(false) .add(SWInfotext(injector) .label(resourceHelper.gs(R.string.needwhitelisting, resourceHelper.gs(R.string.app_name)))) .add(SWBreak(injector)) .add(SWButton(injector) .text(R.string.askforpermission) .visibility { androidPermission.permissionNotGranted(context, Manifest.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS) } .action { androidPermission.askForPermission(activity, Manifest.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS) }) .visibility { androidPermission.permissionNotGranted(activity, Manifest.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS) } .validator { !androidPermission.permissionNotGranted(activity, Manifest.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS) } private val screenPermissionBt = SWScreen(injector, R.string.permission) .skippable(false) .add(SWInfotext(injector) .label(resourceHelper.gs(R.string.needlocationpermission))) .add(SWBreak(injector)) .add(SWButton(injector) .text(R.string.askforpermission) .visibility { androidPermission.permissionNotGranted(activity, Manifest.permission.ACCESS_FINE_LOCATION) } .action { androidPermission.askForPermission(activity, Manifest.permission.ACCESS_FINE_LOCATION) }) .visibility { androidPermission.permissionNotGranted(activity, Manifest.permission.ACCESS_FINE_LOCATION) } .validator { !androidPermission.permissionNotGranted(activity, Manifest.permission.ACCESS_FINE_LOCATION) } private val screenPermissionStore = SWScreen(injector, R.string.permission) .skippable(false) .add(SWInfotext(injector) .label(resourceHelper.gs(R.string.needstoragepermission))) .add(SWBreak(injector)) .add(SWButton(injector) .text(R.string.askforpermission) .visibility { androidPermission.permissionNotGranted(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE) } .action { androidPermission.askForPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE) }) .visibility { androidPermission.permissionNotGranted(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE) } .validator { !androidPermission.permissionNotGranted(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE) } private val screenImport = SWScreen(injector, R.string.nav_import) .add(SWInfotext(injector) .label(R.string.storedsettingsfound)) .add(SWBreak(injector)) .add(SWButton(injector) .text(R.string.nav_import) .action { importExportPrefs.importSharedPreferences(activity) }) .visibility { importExportPrefs.prefsFileExists() && !androidPermission.permissionNotGranted(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE) } private val screenNsClient = SWScreen(injector, R.string.nsclientinternal_title) .skippable(true) .add(SWInfotext(injector) .label(R.string.nsclientinfotext)) .add(SWBreak(injector)) .add(SWButton(injector) .text(R.string.enable_nsclient) .action { configBuilderPlugin.performPluginSwitch(nsClientPlugin, true, PluginType.GENERAL) rxBus.send(EventSWUpdate(true)) } .visibility { !nsClientPlugin.isEnabled(PluginType.GENERAL) }) .add(SWEditUrl(injector) .preferenceId(R.string.key_nsclientinternal_url) .updateDelay(5) .label(R.string.nsclientinternal_url_title) .comment(R.string.nsclientinternal_url_dialogmessage)) .add(SWEditString(injector) .validator { text: String -> text.length >= 12 } .preferenceId(R.string.key_nsclientinternal_api_secret) .updateDelay(5) .label(R.string.nsclientinternal_secret_dialogtitle) .comment(R.string.nsclientinternal_secret_dialogmessage)) .add(SWBreak(injector)) .add(SWEventListener(injector, EventNSClientStatus::class.java) .label(R.string.status) .initialStatus(nsClientPlugin.status) ) .validator { nsClientPlugin.nsClientService != null && NSClientService.isConnected && NSClientService.hasWriteAuth } .visibility { !(nsClientPlugin.nsClientService != null && NSClientService.isConnected && NSClientService.hasWriteAuth) } private val screenPatientName = SWScreen(injector, R.string.patient_name) .skippable(true) .add(SWInfotext(injector) .label(R.string.patient_name_summary)) .add(SWEditString(injector) .validator(SWTextValidator(String::isNotEmpty)) .preferenceId(R.string.key_patient_name)) private val screenMasterPassword = SWScreen(injector, R.string.master_password) .skippable(false) .add(SWInfotext(injector) .label(R.string.master_password)) .add(SWEditEncryptedPassword(injector, cryptoUtil) .preferenceId(R.string.key_master_password)) .add(SWBreak(injector)) .add(SWInfotext(injector) .label(R.string.master_password_summary)) .validator { !cryptoUtil.checkPassword("", sp.getString(R.string.key_master_password, "")) } private val screenAge = SWScreen(injector, R.string.patientage) .skippable(false) .add(SWBreak(injector)) .add(SWRadioButton(injector) .option(R.array.ageArray, R.array.ageValues) .preferenceId(R.string.key_age) .label(R.string.patientage) .comment(R.string.patientage_summary)) .validator { sp.contains(R.string.key_age) } private val screenInsulin = SWScreen(injector, R.string.configbuilder_insulin) .skippable(false) .add(SWPlugin(injector, this) .option(PluginType.INSULIN, R.string.configbuilder_insulin_description) .makeVisible(false) .label(R.string.configbuilder_insulin)) .add(SWBreak(injector)) .add(SWInfotext(injector) .label(R.string.diawarning)) private val screenBgSource = SWScreen(injector, R.string.configbuilder_bgsource) .skippable(false) .add(SWPlugin(injector, this) .option(PluginType.BGSOURCE, R.string.configbuilder_bgsource_description) .label(R.string.configbuilder_bgsource)) .add(SWBreak(injector)) private val screenProfile = SWScreen(injector, R.string.configbuilder_profile) .skippable(false) .add(SWInfotext(injector) .label(R.string.setupwizard_profile_description)) .add(SWBreak(injector)) .add(SWPlugin(injector, this) .option(PluginType.PROFILE, R.string.configbuilder_profile_description) .label(R.string.configbuilder_profile)) private val screenNsProfile = SWScreen(injector, R.string.nsprofile) .skippable(false) .add(SWInfotext(injector) .label(R.string.adjustprofileinns)) .add(SWFragment(injector, this) .add(NSProfileFragment())) .validator { nsProfilePlugin.profile != null && nsProfilePlugin.profile!!.getDefaultProfile() != null && nsProfilePlugin.profile!!.getDefaultProfile()!!.isValid("StartupWizard") } .visibility { nsProfilePlugin.isEnabled(PluginType.PROFILE) } private val screenLocalProfile = SWScreen(injector, R.string.localprofile) .skippable(false) .add(SWFragment(injector, this) .add(LocalProfileFragment())) .validator { localProfilePlugin.profile?.getDefaultProfile()?.isValid("StartupWizard") == true } .visibility { localProfilePlugin.isEnabled(PluginType.PROFILE) } private val screenProfileSwitch = SWScreen(injector, R.string.careportal_profileswitch) .skippable(false) .add(SWInfotext(injector) .label(R.string.profileswitch_ismissing)) .add(SWButton(injector) .text(R.string.doprofileswitch) .action { ProfileSwitchDialog().show(activity.supportFragmentManager, "SetupWizard") }) .validator { profileFunction.getProfile() != null } .visibility { profileFunction.getProfile() == null } private val screenPump = SWScreen(injector, R.string.configbuilder_pump) .skippable(false) .add(SWPlugin(injector, this) .option(PluginType.PUMP, R.string.configbuilder_pump_description) .label(R.string.configbuilder_pump)) .add(SWBreak(injector)) .add(SWInfotext(injector) .label(R.string.setupwizard_pump_pump_not_initialized) .visibility { !isPumpInitialized() }) .add( // Omnipod only SWInfotext(injector) .label(R.string.setupwizard_pump_waiting_for_riley_link_connection) .visibility { val activePump = activePlugin.activePump activePump is OmnipodPumpPlugin && !activePump.isRileyLinkReady }) .add( // Omnipod only SWEventListener(injector, EventRileyLinkDeviceStatusChange::class.java) .label(R.string.setupwizard_pump_riley_link_status) .visibility { activePlugin.activePump is OmnipodPumpPlugin }) .add(SWButton(injector) .text(R.string.readstatus) .action { commandQueue.readStatus("Clicked connect to pump", null) } .visibility { // Hide for Omnipod, because as we don't require a Pod to be paired in the setup wizard, // Getting the status might not be possible activePlugin.activePump !is OmnipodPumpPlugin }) .add(SWEventListener(injector, EventPumpStatusChanged::class.java) .visibility { activePlugin.activePump !is OmnipodPumpPlugin }) .validator { isPumpInitialized() } private fun isPumpInitialized(): Boolean { val activePump = activePlugin.activePump // For Omnipod, consider the pump initialized when a RL has been configured successfully // Users will be prompted to activate a Pod after completing the setup wizard. return activePump.isInitialized || (activePump is OmnipodPumpPlugin && activePump.isRileyLinkReady) } private val screenAps = SWScreen(injector, R.string.configbuilder_aps) .skippable(false) .add(SWInfotext(injector) .label(R.string.setupwizard_aps_description)) .add(SWBreak(injector)) .add(SWPlugin(injector, this) .option(PluginType.APS, R.string.configbuilder_aps_description) .label(R.string.configbuilder_aps)) .add(SWBreak(injector)) .add(SWHtmlLink(injector) .label("https://openaps.readthedocs.io/en/latest/")) .add(SWBreak(injector)) private val screenApsMode = SWScreen(injector, R.string.apsmode_title) .skippable(false) .add(SWRadioButton(injector) .option(R.array.aps_modeArray, R.array.aps_modeValues) .preferenceId(R.string.key_aps_mode).label(R.string.apsmode_title) .comment(R.string.setupwizard_preferred_aps_mode)) .validator { sp.contains(R.string.key_aps_mode) } private val screenLoop = SWScreen(injector, R.string.configbuilder_loop) .skippable(false) .add(SWInfotext(injector) .label(R.string.setupwizard_loop_description)) .add(SWBreak(injector)) .add(SWButton(injector) .text(R.string.enableloop) .action { configBuilderPlugin.performPluginSwitch(loopPlugin, true, PluginType.LOOP) rxBus.send(EventSWUpdate(true)) } .visibility { !loopPlugin.isEnabled(PluginType.LOOP) }) .validator { loopPlugin.isEnabled(PluginType.LOOP) } .visibility { !loopPlugin.isEnabled(PluginType.LOOP) && config.APS } private val screenSensitivity = SWScreen(injector, R.string.configbuilder_sensitivity) .skippable(false) .add(SWInfotext(injector) .label(R.string.setupwizard_sensitivity_description)) .add(SWHtmlLink(injector) .label(R.string.setupwizard_sensitivity_url)) .add(SWBreak(injector)) .add(SWPlugin(injector, this) .option(PluginType.SENSITIVITY, R.string.configbuilder_sensitivity_description) .label(R.string.configbuilder_sensitivity)) private val getScreenObjectives = SWScreen(injector, R.string.objectives) .skippable(false) .add(SWInfotext(injector) .label(R.string.startobjective)) .add(SWBreak(injector)) .add(SWFragment(injector, this) .add(ObjectivesFragment())) .validator { objectivesPlugin.objectives[ObjectivesPlugin.FIRST_OBJECTIVE].isStarted } .visibility { !objectivesPlugin.objectives[ObjectivesPlugin.FIRST_OBJECTIVE].isStarted && config.APS } private fun swDefinitionFull() { // List all the screens here add(screenSetupWizard) //.add(screenLanguage) .add(screenEula) .add(if (isRunningTest()) null else screenPermissionBattery) // cannot mock ask battery optimization .add(screenPermissionBt) .add(screenPermissionStore) .add(screenMasterPassword) .add(screenImport) .add(screenUnits) .add(displaySettings) .add(screenNsClient) .add(screenPatientName) .add(screenAge) .add(screenInsulin) .add(screenBgSource) .add(screenProfile) .add(screenNsProfile) .add(screenLocalProfile) .add(screenProfileSwitch) .add(screenPump) .add(screenAps) .add(screenApsMode) .add(screenLoop) .add(screenSensitivity) .add(getScreenObjectives) } private fun swDefinitionPumpControl() { // List all the screens here add(screenSetupWizard) //.add(screenLanguage) .add(screenEula) .add(if (isRunningTest()) null else screenPermissionBattery) // cannot mock ask battery optimization .add(screenPermissionBt) .add(screenPermissionStore) .add(screenMasterPassword) .add(screenImport) .add(screenUnits) .add(displaySettings) .add(screenNsClient) .add(screenPatientName) .add(screenAge) .add(screenInsulin) .add(screenBgSource) .add(screenProfile) .add(screenNsProfile) .add(screenLocalProfile) .add(screenProfileSwitch) .add(screenPump) .add(screenSensitivity) } private fun swDefinitionNSClient() { // List all the screens here add(screenSetupWizard) //.add(screenLanguage) .add(screenEula) .add(if (isRunningTest()) null else screenPermissionBattery) // cannot mock ask battery optimization .add(screenPermissionStore) .add(screenMasterPassword) .add(screenImport) .add(screenUnits) .add(displaySettings) .add(screenNsClient) //.add(screenBgSource) .add(screenPatientName) .add(screenAge) .add(screenInsulin) .add(screenSensitivity) } init { if (config.APS) swDefinitionFull() else if (config.PUMPCONTROL) swDefinitionPumpControl() else if (config.NSCLIENT) swDefinitionNSClient() } }
agpl-3.0
ffd6dddac125cc4430a04e967e84aac5
49.161137
187
0.683092
4.312755
false
true
false
false
mdaniel/intellij-community
platform/core-impl/src/com/intellij/ide/plugins/PluginSetBuilder.kt
2
11494
// 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", "ReplaceNegatedIsEmptyWithIsNotEmpty") package com.intellij.ide.plugins import com.intellij.core.CoreBundle import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.extensions.PluginId import com.intellij.util.lang.Java11Shim import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap import org.jetbrains.annotations.ApiStatus import org.jetbrains.annotations.Nls import org.jetbrains.annotations.PropertyKey import java.util.* import java.util.function.Predicate import java.util.function.Supplier @ApiStatus.Internal class PluginSetBuilder( val unsortedPlugins: Set<IdeaPluginDescriptorImpl>, ) { private val _moduleGraph = createModuleGraph(unsortedPlugins) private val builder = _moduleGraph.builder() val moduleGraph: SortedModuleGraph = _moduleGraph.sorted(builder) private val enabledPluginIds = HashMap<PluginId, IdeaPluginDescriptorImpl>(unsortedPlugins.size) private val enabledModuleV2Ids = HashMap<String, IdeaPluginDescriptorImpl>(unsortedPlugins.size * 2) constructor(unsortedPlugins: Collection<IdeaPluginDescriptorImpl>) : this(LinkedHashSet(unsortedPlugins)) fun checkPluginCycles(errors: MutableList<Supplier<String>>) { if (builder.isAcyclic) { return } for (component in builder.components) { if (component.size < 2) { continue } for (plugin in component) { plugin.isEnabled = false } val pluginsString = component.joinToString(separator = ", ") { "'${it.name}'" } errors.add(message("plugin.loading.error.plugins.cannot.be.loaded.because.they.form.a.dependency.cycle", pluginsString)) val detailedMessage = StringBuilder() val pluginToString: (IdeaPluginDescriptorImpl) -> String = { "id = ${it.pluginId.idString} (${it.name})" } detailedMessage.append("Detected plugin dependencies cycle details (only related dependencies are included):\n") component .asSequence() .map { Pair(it, pluginToString(it)) } .sortedWith(Comparator.comparing({ it.second }, String.CASE_INSENSITIVE_ORDER)) .forEach { detailedMessage.append(" ").append(it.second).append(" depends on:\n") moduleGraph.getDependencies(it.first).asSequence() .filter { o: IdeaPluginDescriptorImpl -> component.contains(o) } .map(pluginToString) .sortedWith(java.lang.String.CASE_INSENSITIVE_ORDER) .forEach { dep: String? -> detailedMessage.append(" ").append(dep).append("\n") } } PluginManagerCore.getLogger().info(detailedMessage.toString()) } } // Only plugins returned. Not modules. See PluginManagerTest.moduleSort test to understand the issue. private fun getSortedPlugins(): Array<IdeaPluginDescriptorImpl> { val pluginToNumber = Object2IntOpenHashMap<PluginId>(unsortedPlugins.size) pluginToNumber.put(PluginManagerCore.CORE_ID, 0) var number = 0 for (module in moduleGraph.nodes) { // no content, so will be no modules, add it if (module.descriptorPath != null || module.content.modules.isEmpty()) { pluginToNumber.putIfAbsent(module.pluginId, number++) } } val sorted = unsortedPlugins.toTypedArray() Arrays.sort(sorted, Comparator { o1, o2 -> pluginToNumber.getInt(o1.pluginId) - pluginToNumber.getInt(o2.pluginId) }) return sorted } private fun getEnabledModules(): List<IdeaPluginDescriptorImpl> { val result = ArrayList<IdeaPluginDescriptorImpl>(moduleGraph.nodes.size) for (module in moduleGraph.nodes) { if (if (module.moduleName == null) module.isEnabled else enabledModuleV2Ids.containsKey(module.moduleName)) { result.add(module) } } return result } fun computeEnabledModuleMap(disabler: Predicate<IdeaPluginDescriptorImpl>? = null): PluginSetBuilder { val logMessages = ArrayList<String>() m@ for (module in moduleGraph.nodes) { if (module.moduleName == null) { if (module.pluginId != PluginManagerCore.CORE_ID && (!module.isEnabled || (disabler != null && disabler.test(module)))) { continue } } else if (!enabledPluginIds.containsKey(module.pluginId)) { continue } for (ref in module.dependencies.modules) { if (!enabledModuleV2Ids.containsKey(ref.name)) { logMessages.add("Module ${module.moduleName ?: module.pluginId} is not enabled because dependency ${ref.name} is not available") continue@m } } for (ref in module.dependencies.plugins) { if (!enabledPluginIds.containsKey(ref.id)) { logMessages.add("Module ${module.moduleName ?: module.pluginId} is not enabled because dependency ${ref.id} is not available") continue@m } } if (module.moduleName == null) { enabledPluginIds.put(module.pluginId, module) for (v1Module in module.modules) { enabledPluginIds.put(v1Module, module) } if (module.packagePrefix != null) { enabledModuleV2Ids.put(module.pluginId.idString, module) } } else { enabledModuleV2Ids.put(module.moduleName, module) } } if (!logMessages.isEmpty()) { PluginManagerCore.getLogger().info(logMessages.joinToString(separator = "\n")) } return this } fun createPluginSetWithEnabledModulesMap(): PluginSet { return computeEnabledModuleMap().createPluginSet() } fun createPluginSet(incompletePlugins: Collection<IdeaPluginDescriptorImpl> = Collections.emptyList()): PluginSet { val sortedPlugins = getSortedPlugins() val allPlugins = LinkedHashSet<IdeaPluginDescriptorImpl>(sortedPlugins.size + incompletePlugins.size) allPlugins += sortedPlugins allPlugins += incompletePlugins val enabledPlugins = sortedPlugins.filterTo(ArrayList(sortedPlugins.size)) { it.isEnabled } val java11Shim = Java11Shim.INSTANCE return PluginSet( moduleGraph = moduleGraph, allPlugins = java11Shim.copyOf(allPlugins), enabledPlugins = java11Shim.copyOfCollection(enabledPlugins), enabledModuleMap = java11Shim.copyOf(enabledModuleV2Ids), enabledPluginAndV1ModuleMap = java11Shim.copyOf(enabledPluginIds), enabledModules = java11Shim.copyOfCollection(getEnabledModules()), ) } fun checkModules(descriptor: IdeaPluginDescriptorImpl, isDebugLogEnabled: Boolean, log: Logger) { m@ for (item in descriptor.content.modules) { for (ref in item.requireDescriptor().dependencies.modules) { if (!enabledModuleV2Ids.containsKey(ref.name)) { if (isDebugLogEnabled) { log.info("Module ${item.name} is not enabled because dependency ${ref.name} is not available") } continue@m } } for (ref in item.requireDescriptor().dependencies.plugins) { if (!enabledPluginIds.containsKey(ref.id)) { if (isDebugLogEnabled) { log.info("Module ${item.name} is not enabled because dependency ${ref.id} is not available") } continue@m } } enabledModuleV2Ids.put(item.name, descriptor) } } // use only for init plugins internal fun initEnableState( descriptor: IdeaPluginDescriptorImpl, idMap: Map<PluginId, IdeaPluginDescriptorImpl>, disabledRequired: MutableSet<IdeaPluginDescriptorImpl>, disabledPlugins: Set<PluginId>, errors: MutableMap<PluginId, PluginLoadingError>, ): PluginLoadingError? { val isNotifyUser = !descriptor.isImplementationDetail for (incompatibleId in descriptor.incompatibilities) { if (!enabledPluginIds.containsKey(incompatibleId) || disabledPlugins.contains(incompatibleId)) { continue } val presentableName = incompatibleId.idString return PluginLoadingError( plugin = descriptor, detailedMessageSupplier = message("plugin.loading.error.long.ide.contains.conflicting.module", descriptor.name, presentableName), shortMessageSupplier = message("plugin.loading.error.short.ide.contains.conflicting.module", presentableName), isNotifyUser = isNotifyUser, ) } for (dependency in descriptor.pluginDependencies) { val depId = dependency.pluginId if (dependency.isOptional || enabledPluginIds.containsKey(depId)) { continue } val dep = idMap.get(depId) if (dep != null && disabledPlugins.contains(depId)) { // broken/incompatible plugins can be updated, add them anyway disabledRequired.add(dep) } return createCannotLoadError(descriptor, errors, isNotifyUser, depId, dep) } for (item in descriptor.dependencies.plugins) { val depId = item.id if (enabledPluginIds.containsKey(depId)) { continue } val dep = idMap.get(depId) if (dep != null && disabledPlugins.contains(depId)) { // broken/incompatible plugins can be updated, add them anyway disabledRequired.add(dep) } return createCannotLoadError(descriptor, errors, isNotifyUser, depId, dep) } for (item in descriptor.dependencies.modules) { if (enabledModuleV2Ids.containsKey(item.name)) { continue } return PluginLoadingError( plugin = descriptor, detailedMessageSupplier = message("plugin.loading.error.long.depends.on.not.installed.plugin", descriptor.name, item.name), shortMessageSupplier = message("plugin.loading.error.short.depends.on.not.installed.plugin", item.name), isNotifyUser = isNotifyUser, ) } return null } } private fun createCannotLoadError( descriptor: IdeaPluginDescriptorImpl, errors: MutableMap<PluginId, PluginLoadingError>, isNotifyUser: Boolean, depId: PluginId, dep: IdeaPluginDescriptor?, ): PluginLoadingError { val depName = dep?.name return if (depName == null) { val depPresentableId = depId.idString errors.get(depId)?.plugin?.let { PluginLoadingError( plugin = descriptor, detailedMessageSupplier = message( "plugin.loading.error.long.depends.on.failed.to.load.plugin", descriptor.name, it.name ?: depPresentableId, ), shortMessageSupplier = message("plugin.loading.error.short.depends.on.failed.to.load.plugin", depPresentableId), isNotifyUser = isNotifyUser, ) } ?: PluginLoadingError( plugin = descriptor, detailedMessageSupplier = message("plugin.loading.error.long.depends.on.not.installed.plugin", descriptor.name, depPresentableId), shortMessageSupplier = message("plugin.loading.error.short.depends.on.not.installed.plugin", depPresentableId), isNotifyUser = isNotifyUser, ) } else PluginLoadingError( plugin = descriptor, detailedMessageSupplier = message("plugin.loading.error.long.depends.on.disabled.plugin", descriptor.name, depName), shortMessageSupplier = message("plugin.loading.error.short.depends.on.disabled.plugin", depName), isNotifyUser = isNotifyUser, disabledDependency = dep.pluginId, ) } private fun message(key: @PropertyKey(resourceBundle = CoreBundle.BUNDLE) String, vararg params: Any): @Nls Supplier<String> { return Supplier { CoreBundle.message(key, *params) } }
apache-2.0
5306d29bdfa0f1b3d4f41e8035bc29e1
37.834459
138
0.696624
4.51276
false
false
false
false
hsson/card-balance-app
app/src/main/java/se/creotec/chscardbalance2/controller/FoodAboutFragment.kt
1
5318
// Copyright (c) 2017 Alexander Håkansson // // This software is released under the MIT License. // https://opensource.org/licenses/MIT package se.creotec.chscardbalance2.controller import android.net.Uri import android.os.Bundle import android.support.customtabs.CustomTabsIntent import android.support.v4.app.Fragment import android.support.v4.content.ContextCompat import android.text.format.DateUtils import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import com.google.gson.Gson import kotlinx.android.synthetic.main.fragment_restaurant_about.* import se.creotec.chscardbalance2.R import se.creotec.chscardbalance2.model.OpenHour import se.creotec.chscardbalance2.model.Restaurant import se.creotec.chscardbalance2.util.Util import java.util.* class FoodAboutFragment : Fragment() { private var restaurant: Restaurant = Restaurant("") override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) arguments?.let { restaurant = Gson().fromJson(it.getString(ARG_RESTAURANT), Restaurant::class.java) } } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(R.layout.fragment_restaurant_about, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) restaurant_rating_bar.rating = restaurant.rating setOpenHours(restaurant_about_open_now, restaurant_about_open_hours) restaurant_visit_website.setOnClickListener { val webIntent = CustomTabsIntent.Builder() .setToolbarColor(ContextCompat.getColor(requireContext(), R.color.color_primary)) .build() webIntent.launchUrl(context, Uri.parse(restaurant.websiteUrl)) } if (restaurant.averagePrice != 0) { restaurant_about_avg_price.text = getString(R.string.restaurant_about_avg_price, restaurant.averagePrice) } else { restaurant_about_avg_price.text = getString(R.string.restaurant_about_avg_no_price) } restaurant_about_campus.text = getString(R.string.restaurant_about_campus, restaurant.campus) } override fun onResume() { super.onResume() setOpenHours(restaurant_about_open_now, restaurant_about_open_hours) } private fun setOpenHours(openNow: TextView, openHours: TextView) { if (restaurant.dishes.isEmpty()) { showClosed(restaurant_about_open_now, openHours, false) } else { val c = Calendar.getInstance() c.time = Date() restaurant.openHours.forEach { oh -> if (oh.dayOfWeek == c.get(Calendar.DAY_OF_WEEK)) { if (Util.isBetweenHours(oh.startHour, oh.endHour)) { openNow.text = getString(R.string.restaurant_about_open_now) openNow.setTextColor(ContextCompat.getColor(requireContext(), R.color.color_success)) val startFormatted = DateUtils.formatDateTime(activity, OpenHour.toUnixTimeStamp(oh.startHour), DateUtils.FORMAT_SHOW_TIME) val endFormatted = DateUtils.formatDateTime(activity, OpenHour.toUnixTimeStamp(oh.endHour), DateUtils.FORMAT_SHOW_TIME) openHours.text = getString(R.string.restaurant_about_hours_range, startFormatted, endFormatted) return } else { showClosed(openNow, openHours, true, before = OpenHour.isBefore(oh.startHour), openHour = oh) return } } } openNow.text = getString(R.string.restaurant_about_open_today) openNow.setTextColor(ContextCompat.getColor(requireContext(), R.color.color_success)) openHours.text = "" } } private fun showClosed(openNow: TextView, openHours: TextView?, now: Boolean, before: Boolean = false, openHour: OpenHour? = null) { if (now) { openNow.text = getString(R.string.restaurant_about_closed_now) if (before && openHour != null) { val startFormatted = DateUtils.formatDateTime(activity, OpenHour.toUnixTimeStamp(openHour.startHour), DateUtils.FORMAT_SHOW_TIME) openHours?.text = getString(R.string.restaurant_about_opens_at, startFormatted) } else { openHours?.text = "" } } else { openNow.text = getString(R.string.restaurant_about_closed_today) openHours?.text = "" } openNow.setTextColor(ContextCompat.getColor(requireContext(), R.color.color_fail)) } companion object { private val ARG_RESTAURANT = "about_restaurant" fun newInstance(restaurant: Restaurant): FoodAboutFragment { val fragment = FoodAboutFragment() val args = Bundle() val restaurantJSON = Gson().toJson(restaurant, Restaurant::class.java) args.putString(ARG_RESTAURANT, restaurantJSON) fragment.arguments = args return fragment } } }
mit
93bdc443751a77ac81dd784779f12f2a
43.680672
147
0.657326
4.471825
false
false
false
false
ingokegel/intellij-community
plugins/kotlin/project-configuration/src/org/jetbrains/kotlin/idea/configuration/KotlinSetupEnvironmentNotificationProvider.kt
1
6903
// 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.configuration import com.intellij.ide.JavaUiBundle import com.intellij.openapi.fileEditor.FileEditor import com.intellij.openapi.module.Module import com.intellij.openapi.module.ModuleUtilCore import com.intellij.openapi.project.Project import com.intellij.openapi.project.ProjectBundle import com.intellij.openapi.roots.ModuleRootManager import com.intellij.openapi.roots.ModuleRootModificationUtil import com.intellij.openapi.roots.ui.configuration.ProjectSettingsService import com.intellij.openapi.ui.popup.JBPopupFactory import com.intellij.openapi.ui.popup.ListPopup import com.intellij.openapi.ui.popup.PopupStep import com.intellij.openapi.ui.popup.util.BaseListPopupStep import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.PsiFile import com.intellij.psi.PsiManager import com.intellij.ui.EditorNotificationPanel import com.intellij.ui.EditorNotificationProvider import com.intellij.ui.EditorNotificationProvider.CONST_NULL import com.intellij.ui.EditorNotifications import org.jetbrains.kotlin.idea.KotlinLanguage import org.jetbrains.kotlin.idea.base.facet.platform.platform import org.jetbrains.kotlin.idea.base.projectStructure.toModuleGroup import org.jetbrains.kotlin.idea.base.util.createComponentActionLabel import org.jetbrains.kotlin.idea.configuration.ui.KotlinConfigurationCheckerService import org.jetbrains.kotlin.idea.projectConfiguration.KotlinNotConfiguredSuppressedModulesState import org.jetbrains.kotlin.idea.projectConfiguration.KotlinProjectConfigurationBundle import org.jetbrains.kotlin.idea.util.application.runWriteAction import org.jetbrains.kotlin.idea.util.isKotlinFileType import org.jetbrains.kotlin.idea.versions.getLibraryRootsWithIncompatibleAbi import org.jetbrains.kotlin.platform.jvm.isJvm import org.jetbrains.kotlin.psi.KtFile import java.util.function.Function import javax.swing.JComponent // Code is partially copied from com.intellij.codeInsight.daemon.impl.SetupSDKNotificationProvider class KotlinSetupEnvironmentNotificationProvider : EditorNotificationProvider { override fun collectNotificationData(project: Project, file: VirtualFile): Function<in FileEditor, out JComponent?> { if (!file.isKotlinFileType()) { return CONST_NULL } val psiFile = PsiManager.getInstance(project).findFile(file) as? KtFile ?: return CONST_NULL if (psiFile.language !== KotlinLanguage.INSTANCE) { return CONST_NULL } val module = ModuleUtilCore.findModuleForPsiElement(psiFile) ?: return CONST_NULL if (!ModuleRootManager.getInstance(module).fileIndex.isInSourceContent(file)) { return CONST_NULL } if (ModuleRootManager.getInstance(module).sdk == null && psiFile.platform.isJvm()) { return createSetupSdkPanel(project, psiFile) } val configurationChecker = KotlinConfigurationCheckerService.getInstance(module.project) if (!configurationChecker.isSyncing && isNotConfiguredNotificationRequired(module.toModuleGroup()) && !hasAnyKotlinRuntimeInScope(module) && getLibraryRootsWithIncompatibleAbi(module).isEmpty() ) { return createKotlinNotConfiguredPanel(module, getAbleToRunConfigurators(module).toList()) } return CONST_NULL } companion object { private fun createSetupSdkPanel(project: Project, file: PsiFile): Function<in FileEditor, out JComponent?> = Function { fileEditor: FileEditor -> EditorNotificationPanel(fileEditor, EditorNotificationPanel.Status.Warning).apply { text = JavaUiBundle.message("project.sdk.not.defined") createActionLabel(ProjectBundle.message("project.sdk.setup")) { ProjectSettingsService.getInstance(project).chooseAndSetSdk() ?: return@createActionLabel runWriteAction { val module = ModuleUtilCore.findModuleForPsiElement(file) if (module != null) { ModuleRootModificationUtil.setSdkInherited(module) } } } } } private fun createKotlinNotConfiguredPanel(module: Module, configurators: List<KotlinProjectConfigurator>): Function<in FileEditor, out JComponent?> = Function { fileEditor: FileEditor -> EditorNotificationPanel(fileEditor, EditorNotificationPanel.Status.Warning).apply { text = KotlinProjectConfigurationBundle.message("kotlin.not.configured") if (configurators.isNotEmpty()) { val project = module.project createComponentActionLabel(KotlinProjectConfigurationBundle.message("action.text.configure")) { label -> val singleConfigurator = configurators.singleOrNull() if (singleConfigurator != null) { singleConfigurator.apply(project) } else { val configuratorsPopup = createConfiguratorsPopup(project, configurators) configuratorsPopup.showUnderneathOf(label) } } createComponentActionLabel(KotlinProjectConfigurationBundle.message("action.text.ignore")) { KotlinNotConfiguredSuppressedModulesState.suppressConfiguration(module) EditorNotifications.getInstance(project).updateAllNotifications() } } } } private fun KotlinProjectConfigurator.apply(project: Project) { configure(project, emptyList()) EditorNotifications.getInstance(project).updateAllNotifications() checkHideNonConfiguredNotifications(project) } fun createConfiguratorsPopup(project: Project, configurators: List<KotlinProjectConfigurator>): ListPopup { val step = object : BaseListPopupStep<KotlinProjectConfigurator>( KotlinProjectConfigurationBundle.message("title.choose.configurator"), configurators ) { override fun getTextFor(value: KotlinProjectConfigurator?) = value?.presentableText ?: "<none>" override fun onChosen(selectedValue: KotlinProjectConfigurator?, finalChoice: Boolean): PopupStep<*>? { return doFinalStep { selectedValue?.apply(project) } } } return JBPopupFactory.getInstance().createListPopup(step) } } }
apache-2.0
8a961ff216bcbe375d14dcb50d738367
49.021739
158
0.689845
5.825316
false
true
false
false
siosio/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/Utils.kt
1
18222
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.intentions import com.intellij.psi.PsiElement import com.intellij.psi.tree.IElementType import org.jetbrains.kotlin.KtNodeTypes import org.jetbrains.kotlin.builtins.KotlinBuiltIns import org.jetbrains.kotlin.builtins.StandardNames import org.jetbrains.kotlin.builtins.functions.FunctionInvokeDescriptor import org.jetbrains.kotlin.builtins.isKSuspendFunctionType import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall import org.jetbrains.kotlin.idea.core.getDeepestSuperDeclarations import org.jetbrains.kotlin.idea.core.getLastLambdaExpression import org.jetbrains.kotlin.idea.core.replaced import org.jetbrains.kotlin.idea.core.setType import org.jetbrains.kotlin.idea.inspections.collections.isCalling import org.jetbrains.kotlin.idea.search.usagesSearch.descriptor import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.load.java.descriptors.JavaMethodDescriptor import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.* import org.jetbrains.kotlin.resolve.ArrayFqNames import org.jetbrains.kotlin.resolve.bindingContextUtil.isUsedAsExpression import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameUnsafe import org.jetbrains.kotlin.resolve.descriptorUtil.isExtension import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.types.KotlinTypeFactory import org.jetbrains.kotlin.types.isFlexible import org.jetbrains.kotlin.types.typeUtil.builtIns import org.jetbrains.kotlin.types.typeUtil.isUnit import org.jetbrains.kotlin.util.OperatorChecks import org.jetbrains.kotlin.util.OperatorNameConventions import org.jetbrains.kotlin.utils.addToStdlib.safeAs fun KtContainerNode.description(): String? { when (node.elementType) { KtNodeTypes.THEN -> return "if" KtNodeTypes.ELSE -> return "else" KtNodeTypes.BODY -> { when (parent) { is KtWhileExpression -> return "while" is KtDoWhileExpression -> return "do...while" is KtForExpression -> return "for" } } } return null } fun KtCallExpression.isMethodCall(fqMethodName: String): Boolean { val resolvedCall = this.resolveToCall() ?: return false return resolvedCall.resultingDescriptor.fqNameUnsafe.asString() == fqMethodName } // returns assignment which replaces initializer fun splitPropertyDeclaration(property: KtProperty): KtBinaryExpression? { val parent = property.parent val initializer = property.initializer ?: return null val explicitTypeToSet = if (property.typeReference != null) null else initializer.analyze().getType(initializer) val psiFactory = KtPsiFactory(property) var assignment = psiFactory.createExpressionByPattern("$0 = $1", property.nameAsName!!, initializer) assignment = parent.addAfter(assignment, property) as KtBinaryExpression parent.addAfter(psiFactory.createNewLine(), property) property.initializer = null if (explicitTypeToSet != null) { property.setType(explicitTypeToSet) } return assignment } val KtQualifiedExpression.callExpression: KtCallExpression? get() = selectorExpression as? KtCallExpression val KtQualifiedExpression.calleeName: String? get() = (callExpression?.calleeExpression as? KtNameReferenceExpression)?.text fun KtQualifiedExpression.toResolvedCall(bodyResolveMode: BodyResolveMode): ResolvedCall<out CallableDescriptor>? { val callExpression = callExpression ?: return null return callExpression.resolveToCall(bodyResolveMode) ?: return null } fun KtExpression.isExitStatement(): Boolean = when (this) { is KtContinueExpression, is KtBreakExpression, is KtThrowExpression, is KtReturnExpression -> true else -> false } // returns false for call of super, static method or method from package fun KtQualifiedExpression.isReceiverExpressionWithValue(): Boolean { val receiver = receiverExpression if (receiver is KtSuperExpression) return false return analyze().getType(receiver) != null } fun KtExpression.negate(reformat: Boolean = true): KtExpression { val specialNegation = specialNegation(reformat) if (specialNegation != null) return specialNegation return KtPsiFactory(this).createExpressionByPattern("!$0", this, reformat = reformat) } fun KtExpression.resultingWhens(): List<KtWhenExpression> = when (this) { is KtWhenExpression -> listOf(this) + entries.map { it.expression?.resultingWhens() ?: listOf() }.flatten() is KtIfExpression -> (then?.resultingWhens() ?: listOf()) + (`else`?.resultingWhens() ?: listOf()) is KtBinaryExpression -> (left?.resultingWhens() ?: listOf()) + (right?.resultingWhens() ?: listOf()) is KtUnaryExpression -> this.baseExpression?.resultingWhens() ?: listOf() is KtBlockExpression -> statements.lastOrNull()?.resultingWhens() ?: listOf() else -> listOf() } fun KtExpression?.hasResultingIfWithoutElse(): Boolean = when (this) { is KtIfExpression -> `else` == null || then.hasResultingIfWithoutElse() || `else`.hasResultingIfWithoutElse() is KtWhenExpression -> entries.any { it.expression.hasResultingIfWithoutElse() } is KtBinaryExpression -> left.hasResultingIfWithoutElse() || right.hasResultingIfWithoutElse() is KtUnaryExpression -> baseExpression.hasResultingIfWithoutElse() is KtBlockExpression -> statements.lastOrNull().hasResultingIfWithoutElse() else -> false } private fun KtExpression.specialNegation(reformat: Boolean): KtExpression? { val factory = KtPsiFactory(this) when (this) { is KtPrefixExpression -> { if (operationReference.getReferencedName() == "!") { val baseExpression = baseExpression if (baseExpression != null) { val bindingContext = baseExpression.analyze(BodyResolveMode.PARTIAL) val type = bindingContext.getType(baseExpression) if (type != null && KotlinBuiltIns.isBoolean(type)) { return KtPsiUtil.safeDeparenthesize(baseExpression) } } } } is KtBinaryExpression -> { val operator = operationToken if (operator !in NEGATABLE_OPERATORS) return null val left = left ?: return null val right = right ?: return null return factory.createExpressionByPattern( "$0 $1 $2", left, getNegatedOperatorText(operator), right, reformat = reformat ) } is KtIsExpression -> { return factory.createExpressionByPattern( "$0 $1 $2", leftHandSide, if (isNegated) "is" else "!is", typeReference ?: return null, reformat = reformat ) } is KtConstantExpression -> { return when (text) { "true" -> factory.createExpression("false") "false" -> factory.createExpression("true") else -> null } } } return null } private val NEGATABLE_OPERATORS = setOf( KtTokens.EQEQ, KtTokens.EXCLEQ, KtTokens.EQEQEQ, KtTokens.EXCLEQEQEQ, KtTokens.IS_KEYWORD, KtTokens.NOT_IS, KtTokens.IN_KEYWORD, KtTokens.NOT_IN, KtTokens.LT, KtTokens.LTEQ, KtTokens.GT, KtTokens.GTEQ ) private fun getNegatedOperatorText(token: IElementType): String { return when (token) { KtTokens.EQEQ -> KtTokens.EXCLEQ.value KtTokens.EXCLEQ -> KtTokens.EQEQ.value KtTokens.EQEQEQ -> KtTokens.EXCLEQEQEQ.value KtTokens.EXCLEQEQEQ -> KtTokens.EQEQEQ.value KtTokens.IS_KEYWORD -> KtTokens.NOT_IS.value KtTokens.NOT_IS -> KtTokens.IS_KEYWORD.value KtTokens.IN_KEYWORD -> KtTokens.NOT_IN.value KtTokens.NOT_IN -> KtTokens.IN_KEYWORD.value KtTokens.LT -> KtTokens.GTEQ.value KtTokens.LTEQ -> KtTokens.GT.value KtTokens.GT -> KtTokens.LTEQ.value KtTokens.GTEQ -> KtTokens.LT.value else -> throw IllegalArgumentException("The token $token does not have a negated equivalent.") } } internal fun KotlinType.isFlexibleRecursive(): Boolean { if (isFlexible()) return true return arguments.any { !it.isStarProjection && it.type.isFlexibleRecursive() } } val KtIfExpression.branches: List<KtExpression?> get() = ifBranchesOrThis() private fun KtExpression.ifBranchesOrThis(): List<KtExpression?> { if (this !is KtIfExpression) return listOf(this) return listOf(then) + `else`?.ifBranchesOrThis().orEmpty() } fun ResolvedCall<out CallableDescriptor>.resolvedToArrayType(): Boolean = resultingDescriptor.returnType.let { type -> type != null && (KotlinBuiltIns.isArray(type) || KotlinBuiltIns.isPrimitiveArray(type)) } fun KtElement?.isZero() = this?.text == "0" fun KtElement?.isOne() = this?.text == "1" private fun KtExpression.isExpressionOfTypeOrSubtype(predicate: (KotlinType) -> Boolean): Boolean { val returnType = resolveToCall()?.resultingDescriptor?.returnType return returnType != null && (returnType.constructor.supertypes + returnType).any(predicate) } fun KtElement?.isSizeOrLength(): Boolean { if (this !is KtDotQualifiedExpression) return false return when (selectorExpression?.text) { "size" -> receiverExpression.isExpressionOfTypeOrSubtype { type -> KotlinBuiltIns.isArray(type) || KotlinBuiltIns.isPrimitiveArray(type) || KotlinBuiltIns.isCollectionOrNullableCollection(type) || KotlinBuiltIns.isMapOrNullableMap(type) } "length" -> receiverExpression.isExpressionOfTypeOrSubtype(KotlinBuiltIns::isCharSequenceOrNullableCharSequence) else -> false } } private val COUNT_FUNCTIONS = listOf(FqName("kotlin.collections.count"), FqName("kotlin.text.count")) fun KtExpression.isCountCall(): Boolean { val callExpression = this as? KtCallExpression ?: (this as? KtQualifiedExpression)?.callExpression ?: return false return callExpression.isCalling(COUNT_FUNCTIONS) } fun KtDotQualifiedExpression.getLeftMostReceiverExpression(): KtExpression = (receiverExpression as? KtDotQualifiedExpression)?.getLeftMostReceiverExpression() ?: receiverExpression fun KtDotQualifiedExpression.replaceFirstReceiver( factory: KtPsiFactory, newReceiver: KtExpression, safeAccess: Boolean = false ): KtExpression { val replaced = (if (safeAccess) { this.replaced(factory.createExpressionByPattern("$0?.$1", receiverExpression, selectorExpression!!)) } else this) as KtQualifiedExpression val receiver = replaced.receiverExpression when (receiver) { is KtDotQualifiedExpression -> { receiver.replace(receiver.replaceFirstReceiver(factory, newReceiver, safeAccess)) } else -> { receiver.replace(newReceiver) } } return replaced } fun KtDotQualifiedExpression.deleteFirstReceiver(): KtExpression { val receiver = receiverExpression when (receiver) { is KtDotQualifiedExpression -> receiver.deleteFirstReceiver() else -> selectorExpression?.let { return this.replace(it) as KtExpression } } return this } private val ARRAY_OF_METHODS = setOf(ArrayFqNames.ARRAY_OF_FUNCTION) + ArrayFqNames.PRIMITIVE_TYPE_TO_ARRAY.values.toSet() + Name.identifier("emptyArray") fun KtCallExpression.isArrayOfMethod(): Boolean { val resolvedCall = resolveToCall() ?: return false val descriptor = resolvedCall.candidateDescriptor return (descriptor.containingDeclaration as? PackageFragmentDescriptor)?.fqName == StandardNames.BUILT_INS_PACKAGE_FQ_NAME && ARRAY_OF_METHODS.contains(descriptor.name) } fun KtBlockExpression.getParentLambdaLabelName(): String? { val lambdaExpression = getStrictParentOfType<KtLambdaExpression>() ?: return null val callExpression = lambdaExpression.getStrictParentOfType<KtCallExpression>() ?: return null val valueArgument = callExpression.valueArguments.find { it.getArgumentExpression()?.unpackFunctionLiteral(allowParentheses = false) === lambdaExpression } ?: return null val lambdaLabelName = (valueArgument.getArgumentExpression() as? KtLabeledExpression)?.getLabelName() return lambdaLabelName ?: callExpression.getCallNameExpression()?.text } internal fun KtExpression.getCallableDescriptor() = resolveToCall()?.resultingDescriptor fun KtDeclaration.isFinalizeMethod(descriptor: DeclarationDescriptor? = null): Boolean { if (containingClass() == null) return false val function = this as? KtNamedFunction ?: return false return function.name == "finalize" && function.valueParameters.isEmpty() && ((descriptor ?: function.descriptor) as? FunctionDescriptor)?.returnType?.isUnit() == true } fun KtDotQualifiedExpression.isToString(): Boolean { val callExpression = selectorExpression as? KtCallExpression ?: return false val referenceExpression = callExpression.calleeExpression as? KtNameReferenceExpression ?: return false if (referenceExpression.getReferencedName() != "toString") return false val resolvedCall = toResolvedCall(BodyResolveMode.PARTIAL) ?: return false val callableDescriptor = resolvedCall.resultingDescriptor as? CallableMemberDescriptor ?: return false return callableDescriptor.getDeepestSuperDeclarations().any { it.fqNameUnsafe.asString() == "kotlin.Any.toString" } } val FunctionDescriptor.isOperatorOrCompatible: Boolean get() { if (this is JavaMethodDescriptor) { return OperatorChecks.check(this).isSuccess } return isOperator } fun KtPsiFactory.appendSemicolonBeforeLambdaContainingElement(element: PsiElement) { val previousElement = KtPsiUtil.skipSiblingsBackwardByPredicate(element) { it!!.node.elementType in KtTokens.WHITE_SPACE_OR_COMMENT_BIT_SET } if (previousElement != null && previousElement is KtExpression) { previousElement.parent.addAfter(createSemicolon(), previousElement) } } internal fun Sequence<PsiElement>.lastWithPersistedElementOrNull(elementShouldPersist: KtExpression): PsiElement? { var lastElement: PsiElement? = null var checked = false for (element in this) { checked = checked || (element === elementShouldPersist) lastElement = element } return if (checked) lastElement else null } fun KotlinType.reflectToRegularFunctionType(): KotlinType { val isTypeAnnotatedWithExtensionFunctionType = annotations.findAnnotation(StandardNames.FqNames.extensionFunctionType) != null val parameterCount = if (isTypeAnnotatedWithExtensionFunctionType) arguments.size - 2 else arguments.size - 1 val classDescriptor = if (isKSuspendFunctionType) builtIns.getSuspendFunction(parameterCount) else builtIns.getFunction(parameterCount) return KotlinTypeFactory.simpleNotNullType(annotations, classDescriptor, arguments) } private val KOTLIN_BUILTIN_ENUM_FUNCTIONS = listOf(FqName("kotlin.enumValues"), FqName("kotlin.enumValueOf")) private val ENUM_STATIC_METHODS = listOf("values", "valueOf") fun KtElement.isReferenceToBuiltInEnumFunction(): Boolean { return when (this) { is KtTypeReference -> { val target = (parent.getStrictParentOfType<KtTypeArgumentList>() ?: this) .getParentOfTypes(true, KtCallExpression::class.java, KtCallableDeclaration::class.java) when (target) { is KtCallExpression -> target.isCalling(KOTLIN_BUILTIN_ENUM_FUNCTIONS) is KtCallableDeclaration -> { target.anyDescendantOfType<KtCallExpression> { val context = it.analyze(BodyResolveMode.PARTIAL_WITH_CFA) it.isCalling(KOTLIN_BUILTIN_ENUM_FUNCTIONS, context) && it.isUsedAsExpression(context) } } else -> false } } is KtQualifiedExpression -> this.callExpression?.calleeExpression?.text in ENUM_STATIC_METHODS is KtCallExpression -> this.calleeExpression?.text in ENUM_STATIC_METHODS is KtCallableReferenceExpression -> this.callableReference.text in ENUM_STATIC_METHODS else -> false } } val CallableDescriptor.isInvokeOperator: Boolean get() = this is FunctionDescriptor && this !is FunctionInvokeDescriptor && isOperator && name == OperatorNameConventions.INVOKE fun KtCallExpression.canBeReplacedWithInvokeCall(): Boolean { return resolveToCall()?.canBeReplacedWithInvokeCall() == true } fun ResolvedCall<out CallableDescriptor>.canBeReplacedWithInvokeCall(): Boolean { val descriptor = resultingDescriptor as? SimpleFunctionDescriptor ?: return false return (descriptor is FunctionInvokeDescriptor || descriptor.isInvokeOperator) && !descriptor.isExtension } fun CallableDescriptor.receiverType(): KotlinType? = (dispatchReceiverParameter ?: extensionReceiverParameter)?.type fun BuilderByPattern<KtExpression>.appendCallOrQualifiedExpression( call: KtCallExpression, newFunctionName: String ) { val callOrQualified = call.getQualifiedExpressionForSelector() ?: call if (callOrQualified is KtQualifiedExpression) { appendExpression(callOrQualified.receiverExpression) appendFixedText(".") } appendFixedText(newFunctionName) call.valueArgumentList?.let { appendFixedText(it.text) } call.lambdaArguments.firstOrNull()?.let { appendFixedText(it.text) } } fun KtCallExpression.singleLambdaArgumentExpression(): KtLambdaExpression? { return lambdaArguments.singleOrNull()?.getArgumentExpression().safeAs() ?: getLastLambdaExpression() }
apache-2.0
880ee1affdfb930a610a4672818f49ae
42.385714
158
0.723795
5.191453
false
false
false
false
siosio/intellij-community
platform/platform-impl/src/com/intellij/ui/layout/testPanels.kt
1
13442
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. @file:Suppress("HardCodedStringLiteral") package com.intellij.ui.layout import com.intellij.openapi.actionSystem.* import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory import com.intellij.openapi.ui.ComboBox import com.intellij.ui.JBIntSpinner import com.intellij.ui.UIBundle import com.intellij.ui.components.* import java.awt.Dimension import java.awt.GridLayout import java.util.function.Supplier import javax.swing.* /** * See [ShowcaseUiDslAction] */ fun labelRowShouldNotGrow(): JPanel { return panel { row("Create Android module") { CheckBox("FooBar module name foo")() } row("Android module name:") { JTextField("input")() } } } fun secondColumnSmallerPanel(): JPanel { val selectForkButton = JButton("Select Other Fork") val branchCombobox = ComboBox<String>() val diffButton = JButton("Show Diff") val titleTextField = JTextField() val panel = panel { row("Base fork:") { JComboBox<String>(arrayOf())(growX, CCFlags.pushX) selectForkButton(growX) } row("Base branch:") { branchCombobox(growX, pushX) diffButton(growX) } row("Title:") { titleTextField() } row("Description:") { scrollPane(JTextArea()) } } // test scrollPane panel.preferredSize = Dimension(512, 256) return panel } @Suppress("unused") fun visualPaddingsPanelOnlyComboBox(): JPanel { return panel { row("Combobox:") { JComboBox<String>(arrayOf("one", "two"))(growX) } row("Combobox Editable:") { val field = JComboBox<String>(arrayOf("one", "two")) field.isEditable = true field(growX) } } } @Suppress("unused") fun visualPaddingsPanelOnlyButton(): JPanel { return panel { row("Button:") { button("label") {}.constraints(growX) } } } @Suppress("unused") fun visualPaddingsPanelOnlyLabeledScrollPane(): JPanel { return panel { row("Description:") { scrollPane(JTextArea()) } } } @Suppress("unused") fun visualPaddingsPanelOnlyTextField(): JPanel { return panel { row("Text field:") { JTextField("text")() } } } fun visualPaddingsPanel(): JPanel { // we use growX to test right border return panel { row("Text field:") { JTextField("text")() } row("Password:") { JPasswordField("secret")() } row("Combobox:") { JComboBox<String>(arrayOf("one", "two"))(growX) } row("Combobox Editable:") { val field = JComboBox<String>(arrayOf("one", "two")) field.isEditable = true field(growX) } row("Button:") { button("label") {}.constraints(growX) } row("CheckBox:") { CheckBox("enabled")() } row("RadioButton:") { JRadioButton("label")() } row("Spinner:") { JBIntSpinner(0, 0, 7)() } row("Text with browse:") { textFieldWithBrowseButton("File") } // test text baseline alignment row("All:") { cell { JTextField("t")() JPasswordField("secret")() JComboBox<String>(arrayOf("c1", "c2"))(growX) button("b") {} CheckBox("c")() JRadioButton("rb")() } } row("Scroll pane:") { scrollPane(JTextArea("first line baseline equals to label")) } } } fun fieldWithGear(): JPanel { return panel { row("Database:") { JTextField()() gearButton() } row("Master Password:") { JBPasswordField()() } } } fun fieldWithGearWithIndent(): JPanel { return panel { row { row("Database:") { JTextField()() gearButton() } row("Master Password:") { JBPasswordField()() } } } } fun alignFieldsInTheNestedGrid(): JPanel { return panel { buttonGroup { row { RadioButton("In KeePass")() row("Database:") { JTextField()() gearButton() } row("Master Password:") { JBPasswordField()(comment = "Stored using weak encryption.") } } } } } fun noteRowInTheDialog(): JPanel { val passwordField = JPasswordField() return panel { noteRow("Profiler requires access to the kernel-level API.\nEnter the sudo password to allow this. ") row("Sudo password:") { passwordField() } row { CheckBox(UIBundle.message("auth.remember.cb"), true)() } noteRow("Should be an empty row above as a gap. <a href=''>Click me</a>.") { System.out.println("Hello") } } } fun jbTextField(): JPanel { val passwordField = JBPasswordField() return panel { noteRow("Enter credentials for bitbucket.org") row("Username:") { JTextField("develar")() } row("Password:") { passwordField() } row { JBCheckBox(UIBundle.message("auth.remember.cb"), true)() } } } fun cellPanel(): JPanel { return panel { row("Repository:") { cell { ComboBox<String>()(comment = "Use File -> Settings Repository... to configure") JButton("Delete")() } } row { // need some pushx/grow component to test label cell grow policy if there is cell with several components scrollPane(JTextArea()) } } } fun commentAndPanel(): JPanel { return panel { row("Repository:") { cell { checkBox("Auto Sync", comment = "Use File -> Settings Repository... to configure") } } row { panel("Foo", JScrollPane(JTextArea())) } } } fun createLafTestPanel(): JPanel { val spacing = createIntelliJSpacingConfiguration() val panel = JPanel(GridLayout(0, 1, spacing.horizontalGap, spacing.verticalGap)) panel.add(JTextField("text")) panel.add(JPasswordField("secret")) panel.add(ComboBox<String>(arrayOf("one", "two"))) val field = ComboBox<String>(arrayOf("one", "two")) field.isEditable = true panel.add(field) panel.add(JButton("label")) panel.add(CheckBox("enabled")) panel.add(JRadioButton("label")) panel.add(JBIntSpinner(0, 0, 7)) panel.add(textFieldWithHistoryWithBrowseButton(null, "File", FileChooserDescriptorFactory.createSingleFileNoJarsDescriptor())) return panel } fun withVerticalButtons(): JPanel { return panel { row { label("<html>Merging branch <b>foo</b> into <b>bar</b>") } row { scrollPane(JTextArea()).constraints(pushX) cell(isVerticalFlow = true) { button("Accept Yours") {}.constraints(growX) button("Accept Theirs") {}.constraints(growX) button("Merge ...") {}.constraints(growX) } } } } fun withSingleVerticalButton(): JPanel { return panel { row { label("<html>Merging branch <b>foo</b> into <b>bar</b>") } row { scrollPane(JTextArea()).constraints(pushX) cell(isVerticalFlow = true) { button("Merge ...") {}.constraints(growX) } } } } fun titledRows(): JPanel { return panel { titledRow("Async Profiler") { row { browserLink("Async profiler README.md", "https://github.com/jvm-profiling-tools/async-profiler") } row("Agent path:") { textFieldWithBrowseButton("").comment("If field is empty bundled agent will be used") } row("Agent options:") { textFieldWithBrowseButton("").comment("Don't add output format (collapsed is used) or output file options") } } titledRow("Java Flight Recorder") { row("JRE home:") { textFieldWithBrowseButton("").comment("At least OracleJRE 9 or OpenJRE 11 is required to import dump") } } } } fun hideableRow(): JPanel { val dummyTextBinding = PropertyBinding({ "" }, {}) return panel { row("Foo") { textField(dummyTextBinding) } hideableRow("Bar") { row { textField(dummyTextBinding) } hideableRow("Nested hideable") { row { label("Label 1") } row { label("Label 2") } } row { label("Text with largeGapAfter") }.largeGapAfter() row { label("Text without largeGapAfter") } row { label("Last Text with largeGapAfter") }.largeGapAfter() } row { label("Non hideable text") } } } fun spannedCheckbox(): JPanel { return panel { buttonGroup { row { RadioButton("In KeePass")() row("Database:") { // comment can lead to broken layout, so, test it JTextField("test")(comment = "Stored using weak encryption. It is recommended to store on encrypted volume for additional security.") } row { cell { checkBox("Protect master password using PGP key") val comboBox = ComboBox(arrayOf("Foo", "Bar")) comboBox.isVisible = false comboBox(growPolicy = GrowPolicy.MEDIUM_TEXT) } } } row { RadioButton("Do not save, forget passwords after restart")() } } } } fun checkboxRowsWithBigComponents(): JPanel { return panel { row { CheckBox("Sample checkbox label")() } row { CheckBox("Sample checkbox label")() } row { CheckBox("Sample checkbox label")() ComboBox(DefaultComboBoxModel(arrayOf("asd", "asd")))() } row { CheckBox("Sample checkbox label")() } row { CheckBox("Sample checkbox label")() ComboBox(DefaultComboBoxModel(arrayOf("asd", "asd")))() } row { CheckBox("Sample checkbox label")() ComboBox(DefaultComboBoxModel(arrayOf("asd", "asd")))() } row { CheckBox("Sample checkbox label")() JBTextField()() } row { cell(isFullWidth = true) { CheckBox("Sample checkbox label")() } } row { cell(isFullWidth = true) { CheckBox("Sample checkbox label")() JBTextField()() } } row { cell(isFullWidth = true) { CheckBox("Sample checkbox label")() comment("commentary") } } } } // titledRows is not enough to test because component align depends on comment components, so, pure titledRow must be tested fun titledRow(): JPanel { return panel { titledRow("Remote settings") { row("Default notebook name:") { JTextField("")() } row("Spark version:") { JTextField("")() } } } } fun sampleConfigurablePanel(): JPanel { return panel { titledRow("Settings") { row { checkBox("Some test option") } row { checkBox("Another test option") } } titledRow("Options") { row { checkBox("Some test option") } row { buttonGroup("Radio group") { row { radioButton("Option 1") } row { radioButton("Option 2") } } } row { buttonGroup("Radio group") { row { radioButton("Option 1", comment = "Comment for the Option 1") } row { radioButton("Option 2") } } } } titledRow("Test") { row("Header") { JTextField()() } row("Longer Header") { checkBox("Some long description", comment = "Comment for the checkbox with longer header.") } row("Header") { JPasswordField()() } row("Header") { comboBox(DefaultComboBoxModel(arrayOf("Option 1", "Option 2")), { null }, {}) } } } } private data class TestOptions(var threadDumpDelay: Int, var enableLargeIndexing: Boolean, var largeIndexFilesCount: Int) fun checkBoxFollowedBySpinner(): JPanel { val testOptions = TestOptions(50, true, 100) return panel { row(label = "Thread dump capture delay (ms):") { spinner(testOptions::threadDumpDelay, 50, 5000, 50) } row { val c = checkBox("Create", testOptions::enableLargeIndexing).actsAsLabel() spinner(testOptions::largeIndexFilesCount, 100, 1_000_000, 1_000) .enableIf(c.selected) label("files to start background indexing") } } } fun separatorAndComment() : JPanel { return panel { row("Label", separated = true) { textField({ "abc" }, {}).comment("comment") } } } fun rowWithIndent(): JPanel { return panel { row("Zero") { subRowIndent = 0 row("Bar 0") { } } row("One") { subRowIndent = 1 row("Bar 1") { } } row("Two") { subRowIndent = 2 row("Bar 2") { } } } } fun rowWithHiddenComponents(): JPanel { val label1 = JLabel("test1") val label2 = JLabel("test2") val label3 = JLabel("test3") val button1 = object : ToggleAction(Supplier{"button"}, null) { override fun isSelected(e: AnActionEvent): Boolean { return label1.isVisible } override fun setSelected(e: AnActionEvent, state: Boolean) { label1.isVisible = state } } val button2 = object : ToggleAction(Supplier{"button"}, null) { override fun isSelected(e: AnActionEvent): Boolean { return label2.isVisible } override fun setSelected(e: AnActionEvent, state: Boolean) { label2.isVisible = state } } val button3 = object : ToggleAction(Supplier{"button"}, null) { override fun isSelected(e: AnActionEvent): Boolean { return label3.isVisible } override fun setSelected(e: AnActionEvent, state: Boolean) { label3.isVisible = state } } return panel { row { component(ActionManager.getInstance().createActionToolbar(ActionPlaces.UNKNOWN, DefaultActionGroup(button1, button2, button3), true).component) } row { component(label1) } row { component(label2) } row { component(label3) } } }
apache-2.0
e8d5570a3b63225c45c3cae292ad9435
24.652672
149
0.607648
4.208516
false
false
false
false
vovagrechka/fucking-everything
alraune/alraune/src/main/java/bolone/rp/BoloneRP_CompareOperations.kt
1
1153
package bolone.rp import alraune.* import alraune.entity.* import aplight.GelNew import bolone.BoSite import com.github.difflib.DiffUtils import com.github.difflib.UnifiedDiffUtils import pieces100.* import vgrechka.* class BoloneRP_CompareOperations(val p: Params) : Dancer<BoloneRP_CompareOperations.Result> { class Params { var operationID1 by place<String>() var operationID2 by place<String>() } class Result(val diff: String) override fun dance(): Result { clog("p", freakingToStringKotlin(p)) imf() // val operation1 = dbSelectMaybeOperationById(p.operationID1.toLong()) ?: bitch() // val operation2 = dbSelectMaybeOperationById(p.operationID2.toLong()) ?: bitch() // val json1 = jsonize_pretty((operation1.data as Order.Operation).orderAfter) // val json2 = jsonize_pretty((operation2.data as Order.Operation).orderAfter) // val patch = DiffUtils.diff(json1, json2) // val diff = UnifiedDiffUtils.generateUnifiedDiff("json1", "json2", json1.lines(), patch, 1) // .joinToString("\n") // return Result(diff) } }
apache-2.0
d4766745bf4beeb8561fa5eca5535a81
21.607843
100
0.675629
3.780328
false
false
false
false
androidx/androidx
wear/compose/integration-tests/demos/src/main/java/androidx/wear/compose/integration/demos/HorizontalPageIndicatorDemo.kt
3
2939
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.wear.compose.integration.demos import androidx.compose.animation.core.TweenSpec import androidx.compose.animation.core.animateFloatAsState import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.foundation.shape.GenericShape import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import androidx.wear.compose.material.HorizontalPageIndicator import androidx.wear.compose.material.MaterialTheme import androidx.wear.compose.material.PageIndicatorState @Composable fun CustomizedHorizontalPageIndicator() { val maxPages = 6 var selectedPage by remember { mutableStateOf(0) } val animatedSelectedPage by animateFloatAsState( targetValue = selectedPage.toFloat(), animationSpec = TweenSpec(durationMillis = 500) ) val pageIndicatorState: PageIndicatorState = remember { object : PageIndicatorState { override val pageOffset: Float get() = animatedSelectedPage - selectedPage override val selectedPage: Int get() = selectedPage override val pageCount: Int get() = maxPages } } Box(modifier = Modifier.fillMaxSize().padding(6.dp)) { DefaultInlineSlider( modifier = Modifier.align(Alignment.Center), value = selectedPage, segmented = true, valueProgression = 0 until maxPages, onValueChange = { selectedPage = it } ) HorizontalPageIndicator( pageIndicatorState = pageIndicatorState, selectedColor = MaterialTheme.colors.secondary, unselectedColor = MaterialTheme.colors.onSecondary, indicatorSize = 15.dp, indicatorShape = TriangleShape, spacing = 8.dp ) } } private val TriangleShape = GenericShape { size, _ -> moveTo(size.width / 2f, 0f) lineTo(size.width, size.height) lineTo(0f, size.height) }
apache-2.0
8333d0b4a4f7bbadcab68436b3616575
35.7375
75
0.716911
4.665079
false
false
false
false
androidx/androidx
compose/foundation/foundation/src/test/kotlin/androidx/compose/foundation/text/selection/MockCoordinates.kt
3
2808
/* * 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.compose.foundation.text.selection import androidx.compose.ui.layout.AlignmentLine import androidx.compose.ui.geometry.Offset import androidx.compose.ui.geometry.Rect import androidx.compose.ui.layout.LayoutCoordinates import androidx.compose.ui.unit.IntSize class MockCoordinates( override var size: IntSize = IntSize.Zero, var localOffset: Offset = Offset.Zero, var globalOffset: Offset = Offset.Zero, var windowOffset: Offset = Offset.Zero, var rootOffset: Offset = Offset.Zero, var childToLocalOffset: Offset = Offset.Zero, override var isAttached: Boolean = true ) : LayoutCoordinates { val globalToLocalParams = mutableListOf<Offset>() val windowToLocalParams = mutableListOf<Offset>() val localToGlobalParams = mutableListOf<Offset>() val localToWindowParams = mutableListOf<Offset>() val localToRootParams = mutableListOf<Offset>() val childToLocalParams = mutableListOf<Pair<LayoutCoordinates, Offset>>() val localPositionOfParams = mutableListOf<Pair<LayoutCoordinates, Offset>>() override val providedAlignmentLines: Set<AlignmentLine> get() = emptySet() override val parentLayoutCoordinates: LayoutCoordinates? get() = null override val parentCoordinates: LayoutCoordinates? get() = null override fun windowToLocal(relativeToWindow: Offset): Offset { windowToLocalParams += relativeToWindow return localOffset } override fun localToWindow(relativeToLocal: Offset): Offset { localToWindowParams += relativeToLocal return windowOffset } override fun localToRoot(relativeToLocal: Offset): Offset { localToRootParams += relativeToLocal return rootOffset } override fun localPositionOf( sourceCoordinates: LayoutCoordinates, relativeToSource: Offset ): Offset { localPositionOfParams += sourceCoordinates to relativeToSource return childToLocalOffset } override fun localBoundingBoxOf( sourceCoordinates: LayoutCoordinates, clipBounds: Boolean ): Rect = Rect.Zero override fun get(alignmentLine: AlignmentLine): Int = 0 }
apache-2.0
cc339061d50510d529e6f577ef244945
34.1125
80
0.733974
4.909091
false
false
false
false
androidx/androidx
room/room-compiler/src/main/kotlin/androidx/room/writer/DaoWriter.kt
3
28361
/* * Copyright (C) 2016 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.room.writer import androidx.room.compiler.codegen.CodeLanguage import androidx.room.compiler.codegen.VisibilityModifier import androidx.room.compiler.codegen.XClassName import androidx.room.compiler.codegen.XCodeBlock import androidx.room.compiler.codegen.XCodeBlock.Builder.Companion.addLocalVal import androidx.room.compiler.codegen.XFunSpec import androidx.room.compiler.codegen.XFunSpec.Builder.Companion.apply import androidx.room.compiler.codegen.XPropertySpec import androidx.room.compiler.codegen.XTypeName import androidx.room.compiler.codegen.XTypeSpec import androidx.room.compiler.codegen.XTypeSpec.Builder.Companion.addOriginatingElement import androidx.room.compiler.codegen.asClassName import androidx.room.compiler.processing.XElement import androidx.room.compiler.processing.XMethodElement import androidx.room.compiler.processing.XType import androidx.room.ext.CommonTypeNames import androidx.room.ext.RoomMemberNames import androidx.room.ext.RoomTypeNames import androidx.room.ext.RoomTypeNames.DELETE_OR_UPDATE_ADAPTER import androidx.room.ext.RoomTypeNames.INSERTION_ADAPTER import androidx.room.ext.RoomTypeNames.ROOM_DB import androidx.room.ext.RoomTypeNames.SHARED_SQLITE_STMT import androidx.room.ext.RoomTypeNames.UPSERTION_ADAPTER import androidx.room.ext.SupportDbTypeNames import androidx.room.ext.capitalize import androidx.room.processor.OnConflictProcessor import androidx.room.solver.CodeGenScope import androidx.room.solver.KotlinBoxedPrimitiveMethodDelegateBinder import androidx.room.solver.KotlinDefaultMethodDelegateBinder import androidx.room.solver.types.getRequiredTypeConverters import androidx.room.vo.Dao import androidx.room.vo.DeleteOrUpdateShortcutMethod import androidx.room.vo.InsertionMethod import androidx.room.vo.KotlinBoxedPrimitiveMethodDelegate import androidx.room.vo.KotlinDefaultMethodDelegate import androidx.room.vo.QueryMethod import androidx.room.vo.RawQueryMethod import androidx.room.vo.ReadQueryMethod import androidx.room.vo.ShortcutEntity import androidx.room.vo.TransactionMethod import androidx.room.vo.UpdateMethod import androidx.room.vo.UpsertionMethod import androidx.room.vo.WriteQueryMethod import java.util.Arrays import java.util.Collections import java.util.Locale /** * Creates the implementation for a class annotated with Dao. */ class DaoWriter( val dao: Dao, private val dbElement: XElement, codeLanguage: CodeLanguage ) : TypeWriter(codeLanguage) { private val declaredDao = dao.element.type // TODO nothing prevents this from conflicting, we should fix. private val dbProperty: XPropertySpec = XPropertySpec .builder(codeLanguage, DB_PROPERTY_NAME, ROOM_DB, VisibilityModifier.PRIVATE) .build() private val companionTypeBuilder = lazy { XTypeSpec.companionObjectBuilder(codeLanguage) } companion object { const val GET_LIST_OF_TYPE_CONVERTERS_METHOD = "getRequiredConverters" const val DB_PROPERTY_NAME = "__db" private fun shortcutEntityFieldNamePart(shortcutEntity: ShortcutEntity): String { fun typeNameToFieldName(typeName: XClassName): String { return typeName.simpleNames.last() } return if (shortcutEntity.isPartialEntity) { typeNameToFieldName(shortcutEntity.pojo.className) + "As" + typeNameToFieldName(shortcutEntity.entityClassName) } else { typeNameToFieldName(shortcutEntity.entityClassName) } } } override fun createTypeSpecBuilder(): XTypeSpec.Builder { val builder = XTypeSpec.classBuilder(codeLanguage, dao.implTypeName) /** * For prepared statements that perform insert/update/delete/upsert, * we check if there are any arguments of variable length (e.g. "IN (:var)"). * If not, we should re-use the statement. * This requires more work but creates good performance. */ val groupedPreparedQueries = dao.queryMethods .filterIsInstance<WriteQueryMethod>() .groupBy { it.parameters.any { it.queryParamAdapter?.isMultiple ?: true } } // queries that can be prepared ahead of time val preparedQueries = groupedPreparedQueries[false] ?: emptyList() // queries that must be rebuilt every single time val oneOffPreparedQueries = groupedPreparedQueries[true] ?: emptyList() val shortcutMethods = buildList { addAll(createInsertionMethods()) addAll(createDeletionMethods()) addAll(createUpdateMethods()) addAll(createTransactionMethods()) addAll(createPreparedQueries(preparedQueries)) addAll(createUpsertMethods()) } builder.apply { addOriginatingElement(dbElement) setVisibility(VisibilityModifier.PUBLIC) if (dao.element.isInterface()) { addSuperinterface(dao.typeName) } else { superclass(dao.typeName) } addProperty(dbProperty) setPrimaryConstructor( createConstructor( shortcutMethods, dao.constructorParamType != null ) ) shortcutMethods.forEach { addFunction(it.functionImpl) } dao.queryMethods.filterIsInstance<ReadQueryMethod>().forEach { method -> addFunction(createSelectMethod(method)) } oneOffPreparedQueries.forEach { addFunction(createPreparedQueryMethod(it)) } dao.rawQueryMethods.forEach { addFunction(createRawQueryMethod(it)) } if (codeLanguage == CodeLanguage.JAVA) { dao.kotlinDefaultMethodDelegates.forEach { addFunction(createDefaultImplMethodDelegate(it)) } dao.kotlinBoxedPrimitiveMethodDelegates.forEach { addFunction(createBoxedPrimitiveBridgeMethodDelegate(it)) } } // Keep this the last one to be generated because used custom converters will // register fields with a payload which we collect in dao to report used // Type Converters. addConverterListMethod(this) if (companionTypeBuilder.isInitialized()) { addType(companionTypeBuilder.value.build()) } } return builder } private fun addConverterListMethod(typeSpecBuilder: XTypeSpec.Builder) { when (codeLanguage) { // For Java a static method is created CodeLanguage.JAVA -> typeSpecBuilder.addFunction(createConverterListMethod()) // For Kotlin a function in the companion object is created CodeLanguage.KOTLIN -> companionTypeBuilder.value .addFunction(createConverterListMethod()) .build() } } private fun createConverterListMethod(): XFunSpec { val body = XCodeBlock.builder(codeLanguage).apply { val requiredTypeConverters = getRequiredTypeConverters() if (requiredTypeConverters.isEmpty()) { when (language) { CodeLanguage.JAVA -> addStatement("return %T.emptyList()", Collections::class.asClassName()) CodeLanguage.KOTLIN -> addStatement("return emptyList()") } } else { val placeholders = requiredTypeConverters.joinToString(",") { "%L" } val requiredTypeConvertersLiterals = requiredTypeConverters.map { XCodeBlock.ofJavaClassLiteral(language, it) }.toTypedArray() when (language) { CodeLanguage.JAVA -> addStatement("return %T.asList($placeholders)", Arrays::class.asClassName(), *requiredTypeConvertersLiterals ) CodeLanguage.KOTLIN -> addStatement( "return listOf($placeholders)", *requiredTypeConvertersLiterals ) } } }.build() return XFunSpec.builder( codeLanguage, GET_LIST_OF_TYPE_CONVERTERS_METHOD, VisibilityModifier.PUBLIC ).apply( javaMethodBuilder = { addModifiers(javax.lang.model.element.Modifier.STATIC) }, kotlinFunctionBuilder = { addAnnotation(kotlin.jvm.JvmStatic::class) }, ).apply { returns( CommonTypeNames.LIST.parametrizedBy( CommonTypeNames.JAVA_CLASS.parametrizedBy(XTypeName.ANY_WILDCARD) ) ) addCode(body) }.build() } private fun createPreparedQueries( preparedQueries: List<WriteQueryMethod> ): List<PreparedStmtQuery> { return preparedQueries.map { method -> val fieldSpec = getOrCreateProperty(PreparedStatementProperty(method)) val queryWriter = QueryWriter(method) val fieldImpl = PreparedStatementWriter(queryWriter) .createAnonymous(this@DaoWriter, dbProperty) val methodBody = createPreparedQueryMethodBody(method, fieldSpec, queryWriter) PreparedStmtQuery( mapOf(PreparedStmtQuery.NO_PARAM_FIELD to (fieldSpec to fieldImpl)), methodBody ) } } private fun createPreparedQueryMethodBody( method: WriteQueryMethod, preparedStmtField: XPropertySpec, queryWriter: QueryWriter ): XFunSpec { val scope = CodeGenScope(this) method.preparedQueryResultBinder.executeAndReturn( prepareQueryStmtBlock = { val stmtName = getTmpVar("_stmt") builder.addLocalVal( stmtName, SupportDbTypeNames.SQLITE_STMT, "%N.acquire()", preparedStmtField ) queryWriter.bindArgs(stmtName, emptyList(), this) stmtName }, preparedStmtProperty = preparedStmtField, dbProperty = dbProperty, scope = scope ) return overrideWithoutAnnotations(method.element, declaredDao) .addCode(scope.generate()) .build() } private fun createTransactionMethods(): List<PreparedStmtQuery> { return dao.transactionMethods.map { PreparedStmtQuery(emptyMap(), createTransactionMethodBody(it)) } } private fun createTransactionMethodBody(method: TransactionMethod): XFunSpec { val scope = CodeGenScope(this) method.methodBinder.executeAndReturn( returnType = method.returnType, parameterNames = method.parameterNames, daoName = dao.typeName, daoImplName = dao.implTypeName, dbProperty = dbProperty, scope = scope ) return overrideWithoutAnnotations(method.element, declaredDao) .addCode(scope.generate()) .build() } private fun createConstructor( shortcutMethods: List<PreparedStmtQuery>, callSuper: Boolean ): XFunSpec { val body = XCodeBlock.builder(codeLanguage).apply { addStatement("this.%N = %L", dbProperty, dbProperty.name) shortcutMethods.asSequence().filterNot { it.fields.isEmpty() }.map { it.fields.values }.flatten().groupBy { it.first.name }.map { it.value.first() }.forEach { (propertySpec, initExpression) -> addStatement("this.%L = %L", propertySpec.name, initExpression) } }.build() return XFunSpec.constructorBuilder(codeLanguage, VisibilityModifier.PUBLIC).apply { addParameter( typeName = dao.constructorParamType ?: ROOM_DB, name = dbProperty.name ) if (callSuper) { callSuperConstructor(XCodeBlock.of(language, "%L", dbProperty.name)) } addCode(body) }.build() } private fun createSelectMethod(method: ReadQueryMethod): XFunSpec { return overrideWithoutAnnotations(method.element, declaredDao) .addCode(createQueryMethodBody(method)) .build() } private fun createRawQueryMethod(method: RawQueryMethod): XFunSpec { val body = XCodeBlock.builder(codeLanguage).apply { val scope = CodeGenScope(this@DaoWriter) val roomSQLiteQueryVar: String val queryParam = method.runtimeQueryParam val shouldReleaseQuery: Boolean if (queryParam?.isSupportQuery() == true) { roomSQLiteQueryVar = queryParam.paramName shouldReleaseQuery = false } else if (queryParam?.isString() == true) { roomSQLiteQueryVar = scope.getTmpVar("_statement") shouldReleaseQuery = true addLocalVariable( name = roomSQLiteQueryVar, typeName = RoomTypeNames.ROOM_SQL_QUERY, assignExpr = XCodeBlock.of( codeLanguage, "%M(%L, 0)", RoomMemberNames.ROOM_SQL_QUERY_ACQUIRE, queryParam.paramName ), ) } else { // try to generate compiling code. we would've already reported this error roomSQLiteQueryVar = scope.getTmpVar("_statement") shouldReleaseQuery = false addLocalVariable( name = roomSQLiteQueryVar, typeName = RoomTypeNames.ROOM_SQL_QUERY, assignExpr = XCodeBlock.of( codeLanguage, "%M(%S, 0)", RoomMemberNames.ROOM_SQL_QUERY_ACQUIRE, "missing query parameter" ), ) } if (method.returnsValue) { // don't generate code because it will create 1 more error. The original error is // already reported by the processor. method.queryResultBinder.convertAndReturn( roomSQLiteQueryVar = roomSQLiteQueryVar, canReleaseQuery = shouldReleaseQuery, dbProperty = dbProperty, inTransaction = method.inTransaction, scope = scope ) } add(scope.generate()) }.build() return overrideWithoutAnnotations(method.element, declaredDao) .addCode(body) .build() } private fun createPreparedQueryMethod(method: WriteQueryMethod): XFunSpec { return overrideWithoutAnnotations(method.element, declaredDao) .addCode(createPreparedQueryMethodBody(method)) .build() } /** * Groups all insertion methods based on the insert statement they will use then creates all * field specs, EntityInsertionAdapterWriter and actual insert methods. */ private fun createInsertionMethods(): List<PreparedStmtQuery> { return dao.insertionMethods .map { insertionMethod -> val onConflict = OnConflictProcessor.onConflictText(insertionMethod.onConflict) val entities = insertionMethod.entities val fields = entities.mapValues { val spec = getOrCreateProperty(InsertionMethodProperty(it.value, onConflict)) val impl = EntityInsertionAdapterWriter.create(it.value, onConflict) .createAnonymous(this@DaoWriter, dbProperty) spec to impl } val methodImpl = overrideWithoutAnnotations( insertionMethod.element, declaredDao ).apply { addCode(createInsertionMethodBody(insertionMethod, fields)) }.build() PreparedStmtQuery(fields, methodImpl) } } private fun createInsertionMethodBody( method: InsertionMethod, insertionAdapters: Map<String, Pair<XPropertySpec, XTypeSpec>> ): XCodeBlock { if (insertionAdapters.isEmpty() || method.methodBinder == null) { return XCodeBlock.builder(codeLanguage).build() } val scope = CodeGenScope(this) method.methodBinder.convertAndReturn( parameters = method.parameters, adapters = insertionAdapters, dbProperty = dbProperty, scope = scope ) return scope.generate() } /** * Creates EntityUpdateAdapter for each deletion method. */ private fun createDeletionMethods(): List<PreparedStmtQuery> { return createShortcutMethods(dao.deletionMethods, "deletion") { _, entity -> EntityDeletionAdapterWriter.create(entity) .createAnonymous(this@DaoWriter, dbProperty.name) } } /** * Creates EntityUpdateAdapter for each @Update method. */ private fun createUpdateMethods(): List<PreparedStmtQuery> { return createShortcutMethods(dao.updateMethods, "update") { update, entity -> val onConflict = OnConflictProcessor.onConflictText(update.onConflictStrategy) EntityUpdateAdapterWriter.create(entity, onConflict) .createAnonymous(this@DaoWriter, dbProperty.name) } } private fun <T : DeleteOrUpdateShortcutMethod> createShortcutMethods( methods: List<T>, methodPrefix: String, implCallback: (T, ShortcutEntity) -> XTypeSpec ): List<PreparedStmtQuery> { return methods.mapNotNull { method -> val entities = method.entities if (entities.isEmpty()) { null } else { val onConflict = if (method is UpdateMethod) { OnConflictProcessor.onConflictText(method.onConflictStrategy) } else { "" } val fields = entities.mapValues { val spec = getOrCreateProperty( DeleteOrUpdateAdapterProperty(it.value, methodPrefix, onConflict) ) val impl = implCallback(method, it.value) spec to impl } val methodSpec = overrideWithoutAnnotations(method.element, declaredDao).apply { addCode(createDeleteOrUpdateMethodBody(method, fields)) }.build() PreparedStmtQuery(fields, methodSpec) } } } private fun createDeleteOrUpdateMethodBody( method: DeleteOrUpdateShortcutMethod, adapters: Map<String, Pair<XPropertySpec, XTypeSpec>> ): XCodeBlock { if (adapters.isEmpty() || method.methodBinder == null) { return XCodeBlock.builder(codeLanguage).build() } val scope = CodeGenScope(this) method.methodBinder.convertAndReturn( parameters = method.parameters, adapters = adapters, dbProperty = dbProperty, scope = scope ) return scope.generate() } /** * Groups all upsertion methods based on the upsert statement they will use then creates all * field specs, EntityIUpsertionAdapterWriter and actual upsert methods. */ private fun createUpsertMethods(): List<PreparedStmtQuery> { return dao.upsertionMethods .map { upsertionMethod -> val entities = upsertionMethod.entities val fields = entities.mapValues { val spec = getOrCreateProperty(UpsertionAdapterProperty(it.value)) val impl = EntityUpsertionAdapterWriter.create(it.value) .createConcrete(it.value, this@DaoWriter, dbProperty) spec to impl } val methodImpl = overrideWithoutAnnotations( upsertionMethod.element, declaredDao ).apply { addCode(createUpsertionMethodBody(upsertionMethod, fields)) }.build() PreparedStmtQuery(fields, methodImpl) } } private fun createUpsertionMethodBody( method: UpsertionMethod, upsertionAdapters: Map<String, Pair<XPropertySpec, XCodeBlock>> ): XCodeBlock { if (upsertionAdapters.isEmpty() || method.methodBinder == null) { return XCodeBlock.builder(codeLanguage).build() } val scope = CodeGenScope(this) method.methodBinder.convertAndReturn( parameters = method.parameters, adapters = upsertionAdapters, dbProperty = dbProperty, scope = scope ) return scope.generate() } private fun createPreparedQueryMethodBody(method: WriteQueryMethod): XCodeBlock { val scope = CodeGenScope(this) method.preparedQueryResultBinder.executeAndReturn( prepareQueryStmtBlock = { val queryWriter = QueryWriter(method) val sqlVar = getTmpVar("_sql") val stmtVar = getTmpVar("_stmt") val listSizeArgs = queryWriter.prepareQuery(sqlVar, this) builder.addLocalVal( stmtVar, SupportDbTypeNames.SQLITE_STMT, "%N.compileStatement(%L)", dbProperty, sqlVar ) queryWriter.bindArgs(stmtVar, listSizeArgs, this) stmtVar }, preparedStmtProperty = null, dbProperty = dbProperty, scope = scope ) return scope.builder.build() } private fun createQueryMethodBody(method: ReadQueryMethod): XCodeBlock { val queryWriter = QueryWriter(method) val scope = CodeGenScope(this) val sqlVar = scope.getTmpVar("_sql") val roomSQLiteQueryVar = scope.getTmpVar("_statement") queryWriter.prepareReadAndBind(sqlVar, roomSQLiteQueryVar, scope) method.queryResultBinder.convertAndReturn( roomSQLiteQueryVar = roomSQLiteQueryVar, canReleaseQuery = true, dbProperty = dbProperty, inTransaction = method.inTransaction, scope = scope ) return scope.generate() } // TODO(b/251459654): Handle @JvmOverloads in delegating functions with Kotlin codegen. private fun createDefaultImplMethodDelegate(method: KotlinDefaultMethodDelegate): XFunSpec { val scope = CodeGenScope(this) return overrideWithoutAnnotations(method.element, declaredDao).apply { KotlinDefaultMethodDelegateBinder.executeAndReturn( daoName = dao.typeName, daoImplName = dao.implTypeName, methodName = method.element.jvmName, returnType = method.element.returnType, parameterNames = method.element.parameters.map { it.name }, scope = scope ) addCode(scope.generate()) }.build() } private fun createBoxedPrimitiveBridgeMethodDelegate( method: KotlinBoxedPrimitiveMethodDelegate ): XFunSpec { val scope = CodeGenScope(this) return overrideWithoutAnnotations(method.element, declaredDao).apply { KotlinBoxedPrimitiveMethodDelegateBinder.execute( methodName = method.element.jvmName, returnType = method.element.returnType, parameters = method.concreteMethod.parameters.map { it.type.asTypeName() to it.name }, scope = scope ) addCode(scope.generate()) }.build() } private fun overrideWithoutAnnotations( elm: XMethodElement, owner: XType ): XFunSpec.Builder { return XFunSpec.overridingBuilder(codeLanguage, elm, owner) } /** * Represents a query statement prepared in Dao implementation. * * @param fields This map holds all the member properties necessary for this query. The key is * the corresponding parameter name in the defining query method. The value is a pair from the * property declaration to definition. * @param functionImpl The body of the query method implementation. */ data class PreparedStmtQuery( val fields: Map<String, Pair<XPropertySpec, Any>>, val functionImpl: XFunSpec ) { companion object { // The key to be used in `fields` where the method requires a field that is not // associated with any of its parameters const val NO_PARAM_FIELD = "-" } } private class InsertionMethodProperty( val shortcutEntity: ShortcutEntity, val onConflictText: String ) : SharedPropertySpec( baseName = "insertionAdapterOf${shortcutEntityFieldNamePart(shortcutEntity)}", type = INSERTION_ADAPTER.parametrizedBy(shortcutEntity.pojo.typeName) ) { override fun getUniqueKey(): String { return "${shortcutEntity.pojo.typeName}-${shortcutEntity.entityTypeName}$onConflictText" } override fun prepare(writer: TypeWriter, builder: XPropertySpec.Builder) { } } class DeleteOrUpdateAdapterProperty( val shortcutEntity: ShortcutEntity, val methodPrefix: String, val onConflictText: String ) : SharedPropertySpec( baseName = "${methodPrefix}AdapterOf${shortcutEntityFieldNamePart(shortcutEntity)}", type = DELETE_OR_UPDATE_ADAPTER.parametrizedBy(shortcutEntity.pojo.typeName) ) { override fun prepare(writer: TypeWriter, builder: XPropertySpec.Builder) { } override fun getUniqueKey(): String { return "${shortcutEntity.pojo.typeName}-${shortcutEntity.entityTypeName}" + "$methodPrefix$onConflictText" } } class UpsertionAdapterProperty( val shortcutEntity: ShortcutEntity ) : SharedPropertySpec( baseName = "upsertionAdapterOf${shortcutEntityFieldNamePart(shortcutEntity)}", type = UPSERTION_ADAPTER.parametrizedBy(shortcutEntity.pojo.typeName) ) { override fun getUniqueKey(): String { return "${shortcutEntity.pojo.typeName}-${shortcutEntity.entityTypeName}" } override fun prepare(writer: TypeWriter, builder: XPropertySpec.Builder) { } } class PreparedStatementProperty(val method: QueryMethod) : SharedPropertySpec( baseName = "preparedStmtOf${method.element.jvmName.capitalize(Locale.US)}", type = SHARED_SQLITE_STMT ) { override fun prepare(writer: TypeWriter, builder: XPropertySpec.Builder) { } override fun getUniqueKey(): String { return method.query.original } } }
apache-2.0
795db9cd6eb29a0109f4bc7efbbb7c88
38.832865
100
0.61366
5.297161
false
false
false
false
androidx/androidx
compose/ui/ui/src/desktopMain/kotlin/androidx/compose/ui/window/Tray.desktop.kt
3
7435
/* * 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.compose.ui.window import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.SideEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCompositionContext import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.rememberUpdatedState import androidx.compose.ui.geometry.Size import androidx.compose.ui.graphics.painter.Painter import androidx.compose.ui.graphics.toAwtImage import androidx.compose.ui.platform.DesktopPlatform import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.onEach import kotlinx.coroutines.flow.receiveAsFlow import java.awt.PopupMenu import java.awt.SystemTray import java.awt.TrayIcon // In fact, this size doesn't affect anything on Windows/Linux, because they request what they // need, and not what we provide. It only affects macOs. This size will be scaled in asAwtImage to // support DPI=2.0 // Unfortunately I hadn't enough time to find sources from the official docs private val iconSize = when (DesktopPlatform.Current) { // https://doc.qt.io/qt-5/qtwidgets-desktop-systray-example.html (search 22x22) DesktopPlatform.Linux -> Size(22f, 22f) // https://doc.qt.io/qt-5/qtwidgets-desktop-systray-example.html (search 16x16) DesktopPlatform.Windows -> Size(16f, 16f) // https://medium.com/@acwrightdesign/creating-a-macos-menu-bar-application-using-swiftui-54572a5d5f87 DesktopPlatform.MacOS -> Size(22f, 22f) DesktopPlatform.Unknown -> Size(32f, 32f) } /** * `true` if the platform supports tray icons in the taskbar */ val isTraySupported: Boolean get() = SystemTray.isSupported() // TODO(demin): add mouse click/double-click/right click listeners (can we use PointerInputEvent?) /** * Adds tray icon to the platform taskbar if it is supported. * * If tray icon isn't supported by the platform, in the "standard" error output stream * will be printed an error. * * See [isTraySupported] to know if tray icon is supported * (for example to show/hide an option in the application settings) * * @param icon Icon of the tray * @param state State to control tray and show notifications * @param tooltip Hint/tooltip that will be shown to the user * @param menu Context menu of the tray that will be shown to the user on the mouse click (right * click on Windows, left click on macOs). * If it doesn't contain any items then context menu will not be shown. * @param onAction Action performed when user clicks on the tray icon (double click on Windows, * right click on macOs) */ @Suppress("unused") @Composable fun ApplicationScope.Tray( icon: Painter, state: TrayState = rememberTrayState(), tooltip: String? = null, onAction: () -> Unit = {}, menu: @Composable MenuScope.() -> Unit = {} ) { if (!isTraySupported) { DisposableEffect(Unit) { // We should notify developer, but shouldn't throw an exception. // If we would throw an exception, some application wouldn't work on some platforms at // all, if developer doesn't check that application crashes. // // We can do this because we don't return anything in Tray function, and following // code doesn't depend on something that is created/calculated in this function. System.err.println( "Tray is not supported on the current platform. " + "Use the global property `isTraySupported` to check." ) onDispose {} } return } val currentOnAction by rememberUpdatedState(onAction) val awtIcon = remember(icon) { // We shouldn't use LocalDensity here because Tray's density doesn't equal it. It // equals to the density of the screen on which it shows. Currently Swing doesn't // provide us such information, it only requests an image with the desired width/height // (see MultiResolutionImage.getResolutionVariant). Resources like svg/xml should look okay // because they don't use absolute '.dp' values to draw, they use values which are // relative to their viewport. icon.toAwtImage(GlobalDensity, GlobalLayoutDirection, iconSize) } val tray = remember { TrayIcon(awtIcon).apply { isImageAutoSize = true addActionListener { currentOnAction() } } } val popupMenu = remember { PopupMenu() } val currentMenu by rememberUpdatedState(menu) SideEffect { if (tray.image != awtIcon) tray.image = awtIcon if (tray.toolTip != tooltip) tray.toolTip = tooltip } val composition = rememberCompositionContext() val coroutineScope = rememberCoroutineScope() DisposableEffect(Unit) { tray.popupMenu = popupMenu val menuComposition = popupMenu.setContent(composition) { currentMenu() } SystemTray.getSystemTray().add(tray) state.notificationFlow .onEach(tray::displayMessage) .launchIn(coroutineScope) onDispose { menuComposition.dispose() SystemTray.getSystemTray().remove(tray) } } } /** * Creates a [WindowState] that is remembered across compositions. */ @Composable fun rememberTrayState() = remember { TrayState() } /** * A state object that can be hoisted to control tray and show notifications. * * In most cases, this will be created via [rememberTrayState]. */ class TrayState { private val notificationChannel = Channel<Notification>(0) /** * Flow of notifications sent by [sendNotification]. * This flow doesn't have a buffer, so all previously sent notifications will not appear in * this flow. */ val notificationFlow: Flow<Notification> get() = notificationChannel.receiveAsFlow() /** * Send notification to tray. If [TrayState] is attached to [Tray], notification will be sent to * the platform. If [TrayState] is not attached then notification will be lost. */ fun sendNotification(notification: Notification) { notificationChannel.trySend(notification) } } private fun TrayIcon.displayMessage(notification: Notification) { val messageType = when (notification.type) { Notification.Type.None -> TrayIcon.MessageType.NONE Notification.Type.Info -> TrayIcon.MessageType.INFO Notification.Type.Warning -> TrayIcon.MessageType.WARNING Notification.Type.Error -> TrayIcon.MessageType.ERROR } displayMessage(notification.title, notification.message, messageType) }
apache-2.0
af9eb5768fe1996d4130c3a1de839a2b
36.550505
106
0.707061
4.433512
false
false
false
false
androidx/androidx
fragment/fragment-lint/src/main/java/androidx/fragment/lint/FragmentIssueRegistry.kt
3
1861
/* * Copyright 2019 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.fragment.lint import com.android.tools.lint.client.api.IssueRegistry import com.android.tools.lint.client.api.Vendor import com.android.tools.lint.detector.api.CURRENT_API /** * Issue Registry containing Fragment specific lint Issues. */ @Suppress("UnstableApiUsage") class FragmentIssueRegistry : IssueRegistry() { // tests are run with this version. We ensure that with ApiLintVersionsTest override val api = 13 override val minApi = CURRENT_API override val issues get() = listOf( FragmentTagDetector.ISSUE, UnsafeFragmentLifecycleObserverDetector.ADD_MENU_PROVIDER_ISSUE, UnsafeFragmentLifecycleObserverDetector.BACK_PRESSED_ISSUE, UnsafeFragmentLifecycleObserverDetector.LIVEDATA_ISSUE, UseRequireInsteadOfGet.ISSUE, UseGetLayoutInflater.ISSUE, OnCreateDialogIncorrectCallbackDetector.ISSUE, UnsafeRepeatOnLifecycleDetector.ISSUE, AttachAndDetachInSameTransactionDetector.DETACH_ATTACH_OPERATIONS_ISSUE ) override val vendor = Vendor( feedbackUrl = "https://issuetracker.google.com/issues/new?component=460964", identifier = "androidx.fragment", vendorName = "Android Open Source Project", ) }
apache-2.0
a4ae1b4b89fdf9a416359bbba7d6fad0
38.595745
84
0.747448
4.51699
false
false
false
false
GunoH/intellij-community
plugins/kotlin/gradle/gradle-java/src/org/jetbrains/kotlin/idea/gradleJava/scripting/legacy/GradleStandaloneScriptActions.kt
2
1723
// 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.gradleJava.scripting.legacy import com.intellij.openapi.vfs.VirtualFile import org.jetbrains.kotlin.idea.core.script.settings.KotlinScriptingSettings import org.jetbrains.kotlin.idea.gradleJava.scripting.roots.GradleBuildRootsManager import org.jetbrains.kotlin.scripting.definitions.findScriptDefinition class GradleStandaloneScriptActions( val manager: GradleStandaloneScriptActionsManager, val file: VirtualFile, val isFirstLoad: Boolean, private val doLoad: () -> Unit ) { val project get() = manager.project private val scriptDefinition get() = file.findScriptDefinition(project) private val isAutoReloadAvailable: Boolean private val isAutoReloadEnabled: Boolean init { val scriptDefinition = scriptDefinition if (scriptDefinition != null) { isAutoReloadAvailable = true isAutoReloadEnabled = KotlinScriptingSettings.getInstance(project) .autoReloadConfigurations(scriptDefinition) } else { isAutoReloadAvailable = false isAutoReloadEnabled = false } } fun enableAutoReload() { KotlinScriptingSettings.getInstance(project).setAutoReloadConfigurations(scriptDefinition!!, true) doLoad() updateNotification() } fun reload() { doLoad() manager.remove(file) } fun updateNotification() { GradleBuildRootsManager.getInstance(project)?.updateNotifications(false) { it == file.path } } }
apache-2.0
48be8fd8136cb0fc81e6e9375cc191ad
32.153846
158
0.709228
5.285276
false
false
false
false
GunoH/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/SpecifyOverrideExplicitlyFix.kt
4
5244
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.quickfix import com.intellij.codeInsight.intention.IntentionAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.descriptors.ConstructorDescriptor import org.jetbrains.kotlin.descriptors.ValueParameterDescriptor import org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.diagnostics.Errors import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyzeWithContent import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.KotlinQuickFixAction import org.jetbrains.kotlin.idea.core.ShortenReferences import org.jetbrains.kotlin.idea.core.overrideImplement.BodyType import org.jetbrains.kotlin.idea.core.overrideImplement.OverrideMemberChooserObject import org.jetbrains.kotlin.idea.core.overrideImplement.generateMember import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.renderer.DescriptorRenderer import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.DescriptorToSourceUtils class SpecifyOverrideExplicitlyFix( element: KtClassOrObject, private val signature: String ) : KotlinQuickFixAction<KtClassOrObject>(element) { override fun getText() = KotlinBundle.message("specify.override.for.0.explicitly", signature) override fun getFamilyName() = KotlinBundle.message("specify.override.explicitly") override fun invoke(project: Project, editor: Editor?, file: KtFile) { val element = element ?: return val context = element.analyzeWithContent() val delegatedDescriptor = context.diagnostics.forElement(element).mapNotNull { if (it.factory == Errors.DELEGATED_MEMBER_HIDES_SUPERTYPE_OVERRIDE) Errors.DELEGATED_MEMBER_HIDES_SUPERTYPE_OVERRIDE.cast(it).a else null }.firstOrNull { DescriptorRenderer.ONLY_NAMES_WITH_SHORT_TYPES.render(it) == signature } ?: return for (specifier in element.superTypeListEntries) { if (specifier is KtDelegatedSuperTypeEntry) { val superType = specifier.typeReference?.let { context[BindingContext.TYPE, it] } ?: continue val superTypeDescriptor = superType.constructor.declarationDescriptor as? ClassDescriptor ?: continue val overriddenDescriptor = delegatedDescriptor.overriddenDescriptors.find { it.containingDeclaration == superTypeDescriptor } ?: continue val delegateExpression = specifier.delegateExpression as? KtNameReferenceExpression val delegateTargetDescriptor = context[BindingContext.REFERENCE_TARGET, delegateExpression] ?: return if (delegateTargetDescriptor is ValueParameterDescriptor && delegateTargetDescriptor.containingDeclaration.let { it is ConstructorDescriptor && it.isPrimary && it.containingDeclaration == delegatedDescriptor.containingDeclaration } ) { val delegateParameter = DescriptorToSourceUtils.descriptorToDeclaration( delegateTargetDescriptor ) as? KtParameter if (delegateParameter != null && !delegateParameter.hasValOrVar()) { val factory = KtPsiFactory(project) delegateParameter.addModifier(KtTokens.PRIVATE_KEYWORD) delegateParameter.addAfter(factory.createValKeyword(), delegateParameter.modifierList) } } val overrideMemberChooserObject = OverrideMemberChooserObject.create( project, delegatedDescriptor, overriddenDescriptor, BodyType.Delegate(delegateTargetDescriptor.name.asString()) ) val member = overrideMemberChooserObject.generateMember(element, copyDoc = false) val insertedMember = element.addDeclaration(member) ShortenReferences.DEFAULT.process(insertedMember) return } } } companion object : KotlinSingleIntentionActionFactory() { override fun createAction(diagnostic: Diagnostic): IntentionAction? { val hidesOverrideError = Errors.DELEGATED_MEMBER_HIDES_SUPERTYPE_OVERRIDE.cast(diagnostic) val klass = hidesOverrideError.psiElement if (klass.superTypeListEntries.any { it is KtDelegatedSuperTypeEntry && it.delegateExpression !is KtNameReferenceExpression }) { return null } val properOverride = hidesOverrideError.a return SpecifyOverrideExplicitlyFix(klass, DescriptorRenderer.ONLY_NAMES_WITH_SHORT_TYPES.render(properOverride)) } } }
apache-2.0
d07c106656f436f630b29d2d9b6be849
52.520408
158
0.694317
5.8202
false
false
false
false
GunoH/intellij-community
plugins/github/src/org/jetbrains/plugins/github/pullrequest/data/GHPRGraphFileHistory.kt
2
2760
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.github.pullrequest.data import com.intellij.openapi.diff.impl.patch.TextFilePatch import com.intellij.util.asSafely import org.jetbrains.plugins.github.api.data.GHCommit import java.util.concurrent.ConcurrentHashMap class GHPRGraphFileHistory(private val commitsMap: Map<String, GHCommitWithPatches>, private val lastCommit: GHCommit, private val finalFilePath: String) : GHPRFileHistory { private val containsCache = ConcurrentHashMap<Pair<String, String>, Boolean>() override fun contains(commitSha: String, filePath: String): Boolean = containsCache.getOrPut(commitSha to filePath) { val lastCommitWithPatches = commitsMap[lastCommit.oid] ?: return@getOrPut false isSameFile(lastCommitWithPatches, finalFilePath, commitSha, filePath) } private fun isSameFile(knownCommit: GHCommitWithPatches, knownFilePath: String, commitSha: String, filePath: String): Boolean { if (knownCommit.cumulativePatches.none { it.asSafely<TextFilePatch>()?.filePath == knownFilePath }) return false val newKnownFilePath = knownCommit.commitPatches.find { it.asSafely<TextFilePatch>()?.filePath == knownFilePath }?.beforeFileName if (knownCommit.sha == commitSha && (knownFilePath == filePath || newKnownFilePath == filePath)) return true val knownParents = knownCommit.commit.parents.mapNotNull { commitsMap[it.oid] } return knownParents.any { isSameFile(it, newKnownFilePath ?: knownFilePath, commitSha, filePath) } } override fun compare(commitSha1: String, commitSha2: String): Int { TODO("Not supported for now") /*if (commitSha1 == commitSha2) return 0 val commit1 = commitsMap[commitSha1] ?: error("Invalid commit sha: $commitSha1") val commit2 = commitsMap[commitSha2] ?: error("Invalid commit sha: $commitSha2") // check if commitSha2 is a parent of commitSha1 for (commit in Traverser.forGraph(commitsGraph).depthFirstPreOrder(commit1.commit)) { if (commit == commit2.commit) return 1 } // check if commitSha1 is a parent of commitSha2 for (commit in Traverser.forGraph(commitsGraph).depthFirstPreOrder(commit2.commit)) { if (commit == commit1.commit) return -1 } // We break contract here by returning -2 for unconnected commits return -2*/ } override fun getPatches(parent: String, child: String, includeFirstKnownPatch: Boolean, includeLastPatch: Boolean): List<TextFilePatch> { TODO("Not supported for now") } companion object { private val TextFilePatch.filePath get() = (afterName ?: beforeName)!! } }
apache-2.0
fa87c7b6b069b3c449541f62b08cc45f
46.586207
140
0.737319
4.33281
false
false
false
false
siosio/intellij-community
plugins/kotlin/common/src/org/jetbrains/kotlin/resolve/scopes/ExplicitImportsScope.kt
2
1596
// 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.resolve.scopes import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.incremental.components.LookupLocation import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.utils.Printer import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstanceOrNull class ExplicitImportsScope(private val descriptors: Collection<DeclarationDescriptor>) : BaseImportingScope(null) { override fun getContributedClassifier(name: Name, location: LookupLocation) = descriptors.filter { it.name == name }.firstIsInstanceOrNull<ClassifierDescriptor>() override fun getContributedPackage(name: Name) = descriptors.filter { it.name == name }.firstIsInstanceOrNull<PackageViewDescriptor>() override fun getContributedVariables(name: Name, location: LookupLocation) = descriptors.filter { it.name == name }.filterIsInstance<VariableDescriptor>() override fun getContributedFunctions(name: Name, location: LookupLocation) = descriptors.filter { it.name == name }.filterIsInstance<FunctionDescriptor>() override fun getContributedDescriptors( kindFilter: DescriptorKindFilter, nameFilter: (Name) -> Boolean, changeNamesForAliased: Boolean ) = descriptors override fun computeImportedNames() = descriptors.mapTo(hashSetOf()) { it.name } override fun printStructure(p: Printer) { p.println(this::class.java.name) } }
apache-2.0
0bc23fd6a979a960bbfdf8f1e1e7655c
45.941176
158
0.765038
4.956522
false
false
false
false
Stealth2800/MCMarkupLanguage2
src/test/kotlin/com/stealthyone/mcml2/McmlParserTest.kt
1
13501
/** * Copyright 2017 Stealth2800 <http://stealthyone.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 com.stealthyone.mcml2 import net.md_5.bungee.api.ChatColor import net.md_5.bungee.api.chat.BaseComponent import net.md_5.bungee.api.chat.ClickEvent import net.md_5.bungee.api.chat.ComponentBuilder import net.md_5.bungee.api.chat.HoverEvent import net.md_5.bungee.api.chat.TextComponent import org.junit.Test class McmlParserTest { private val parser = McmlParser() private fun translate(str: String): String { return ChatColor.translateAlternateColorCodes('&', str) } private fun assertMcmlEquals(raw: String, expected: Array<out BaseComponent>, replacements: Map<String, Any>? = null) { val res = parser.parse(raw, replacements) assert(expected.size == res.size) { "Input string '$raw' failed test: invalid number of results: \nParsed:\n\t${res.joinToString("\n\t")}" } for ((i, component) in expected.withIndex()) { val str1 = component.toString() val str2 = res[i].toString() assert(str1 == str2) { "Input string '$raw' failed test:\nParsed: $str2\nExpected: $str1" } } } @Test fun replaceTest() { assertMcmlEquals( translate("Hello {1} This is an {2} test!"), ComponentBuilder("Hello WORLD This is an AWESOME test!").create(), mapOf("{1}" to "WORLD", "{2}" to "AWESOME") ) assertMcmlEquals( translate("Hello {1} there!"), ComponentBuilder("Hello [Hello](\"Hover Text!\") there!").create(), mapOf("{1}" to "[Hello](\"Hover Text!\")") ) assertMcmlEquals( translate("Hello {word1} this is a {word2}"), ComponentBuilder("Hello WORLD this is a TEST").create(), mapOf("{word1}" to "WORLD", "{word2}" to "TEST") ) assertMcmlEquals( translate("Hello {word1} this is a {word2}"), ComponentBuilder("Hello WORLD {word2} this is a TEST").create(), mapOf("{word1}" to "WORLD {word2}", "{word2}" to "TEST") ) assertMcmlEquals( translate("Hello {word1} this is the same {word1}"), ComponentBuilder("Hello WORLD this is the same WORLD").create(), mapOf("{word1}" to "WORLD") ) } @Test fun colorsTest() { // Single word assertMcmlEquals(translate("Hello!"), ComponentBuilder("Hello!").create()) assertMcmlEquals(translate("&aHello!"), ComponentBuilder("Hello!").color(ChatColor.GREEN).create()) assertMcmlEquals(translate("&a&lHello!"), ComponentBuilder("Hello!").color(ChatColor.GREEN).bold(true).create()) assertMcmlEquals(translate("&lHello!"), ComponentBuilder("Hello!").bold(true).create()) assertMcmlEquals(translate("&aHello!&l"), ComponentBuilder("Hello!").color(ChatColor.GREEN).create()) // Two words assertMcmlEquals(translate("Hello World!"), ComponentBuilder("Hello World!").create()) assertMcmlEquals(translate("&aHello World!"), ComponentBuilder("Hello World!").color(ChatColor.GREEN).create()) assertMcmlEquals(translate("Hello &bWorld!"), ComponentBuilder("Hello ").append("World!").color(ChatColor.AQUA).create()) assertMcmlEquals(translate("&aHello &bWorld!"), ComponentBuilder("Hello ").color(ChatColor.GREEN).append("World!").color(ChatColor.AQUA).create()) assertMcmlEquals(translate("&a&lHello World!"), ComponentBuilder("Hello World!").color(ChatColor.GREEN).bold(true).create()) assertMcmlEquals(translate("&a&lHello &bWorld!"), ComponentBuilder("Hello ").color(ChatColor.GREEN).bold(true) .append("World!", ComponentBuilder.FormatRetention.NONE).color(ChatColor.AQUA).create()) assertMcmlEquals(translate("&a&l&oHello World!"), ComponentBuilder("Hello World!").color(ChatColor.GREEN).bold(true).italic(true).create()) assertMcmlEquals(translate("&a&l&oHello &bWorld!"), ComponentBuilder("Hello ").color(ChatColor.GREEN).bold(true).italic(true) .append("World!", ComponentBuilder.FormatRetention.NONE).color(ChatColor.AQUA).create()) assertMcmlEquals(translate("&a&l&oHello &mWorld!"), ComponentBuilder("Hello ").color(ChatColor.GREEN).bold(true).italic(true) .append("World!").strikethrough(true).create()) assertMcmlEquals(translate("&aHello &b&lWorld!"), ComponentBuilder("Hello ").color(ChatColor.GREEN) .append("World!").color(ChatColor.AQUA).bold(true).create()) assertMcmlEquals(translate("Hello &aWorld &lthis &b&a&lis &rsupposed to be &4complicate&9d"), ComponentBuilder("Hello ") .append("World ").color(ChatColor.GREEN) .append("this ").bold(true) .append("is ").color(ChatColor.GREEN).bold(true) .append("supposed to be ", ComponentBuilder.FormatRetention.NONE) .append("complicate").color(ChatColor.DARK_RED) .append("d").color(ChatColor.BLUE).create()) } @Test fun eventsTest() { assertMcmlEquals(translate("""Click [here](>"google.com" "Click to open link")!"""), ComponentBuilder("Click ").append("here") .event(ClickEvent(ClickEvent.Action.OPEN_URL, "google.com")) .event(HoverEvent(HoverEvent.Action.SHOW_TEXT, ComponentBuilder("Click to open link").create())) .append("!", ComponentBuilder.FormatRetention.NONE) .create()) assertMcmlEquals(translate("""This "is" a [quote](!"/say \"hello\" world!" "One \"more\" quote!")"""), ComponentBuilder("""This "is" a """).append("quote") .event(ClickEvent(ClickEvent.Action.RUN_COMMAND, """/say "hello" world!""")) .event(HoverEvent(HoverEvent.Action.SHOW_TEXT, ComponentBuilder("""One "more" quote!""").create())) .create()) assertMcmlEquals(translate("""[Click!](!"/say hello")"""), ComponentBuilder("Click!") .event(ClickEvent(ClickEvent.Action.RUN_COMMAND, "/say hello")).create()) assertMcmlEquals(translate("""[Click!](!"/profile")"""), ComponentBuilder("Click!") .event(ClickEvent(ClickEvent.Action.RUN_COMMAND, "/profile")).create()) assertMcmlEquals(translate("""[Hover!]("&aHello!")"""), ComponentBuilder("Hover!") .event(HoverEvent(HoverEvent.Action.SHOW_TEXT, ComponentBuilder("Hello!").color(ChatColor.GREEN).create())) .create()) assertMcmlEquals(translate("""[Click!](!"/say hello" "Message")"""), ComponentBuilder("Click!") .event(ClickEvent(ClickEvent.Action.RUN_COMMAND, "/say hello")) .event(HoverEvent(HoverEvent.Action.SHOW_TEXT, ComponentBuilder("Message").create())) .create()) assertMcmlEquals(translate("""Text[Click!](!"/say hello" "Message")"""), ComponentBuilder("Text") .append("Click!") .event(ClickEvent(ClickEvent.Action.RUN_COMMAND, "/say hello")) .event(HoverEvent(HoverEvent.Action.SHOW_TEXT, ComponentBuilder("Message").create())) .create()) assertMcmlEquals(translate("""&aText[Click!](!"/say hello" "Message")"""), ComponentBuilder("Text").color(ChatColor.GREEN) .append("Click!") .event(ClickEvent(ClickEvent.Action.RUN_COMMAND, "/say hello")) .event(HoverEvent(HoverEvent.Action.SHOW_TEXT, ComponentBuilder("Message").create())) .create()) assertMcmlEquals(translate("""Text [&aClick!](!"/say hello" "Message")"""), ComponentBuilder("Text ") .append("Click!").color(ChatColor.GREEN) .event(ClickEvent(ClickEvent.Action.RUN_COMMAND, "/say hello")) .event(HoverEvent(HoverEvent.Action.SHOW_TEXT, ComponentBuilder("Message").create())).create()) assertMcmlEquals(translate("""&aText [&bClick!](!"/say hello" "Message")"""), ComponentBuilder("Text ").color(ChatColor.GREEN) .append("Click!").color(ChatColor.AQUA) .event(ClickEvent(ClickEvent.Action.RUN_COMMAND, "/say hello")) .event(HoverEvent(HoverEvent.Action.SHOW_TEXT, ComponentBuilder("Message").create())) .create()) assertMcmlEquals(translate("""&bText [Click &ahere!](!"/say hello" "&aCol&4ored &b&lMessage&o!")"""), ComponentBuilder("Text ").color(ChatColor.AQUA) .append("Click ") .event(ClickEvent(ClickEvent.Action.RUN_COMMAND, "/say hello")) .event(HoverEvent(HoverEvent.Action.SHOW_TEXT, ComponentBuilder("Col").color(ChatColor.GREEN) .append("ored ").color(ChatColor.DARK_RED) .append("Message").color(ChatColor.AQUA).bold(true) .append("!").italic(true).create())) .append("here!").color(ChatColor.GREEN) .create()) assertMcmlEquals(translate("Example [broadcast](\"&aSupports hover text!\") message"), ComponentBuilder("Example ") .append("broadcast") .event(HoverEvent(HoverEvent.Action.SHOW_TEXT, ComponentBuilder("Supports hover text!") .color(ChatColor.GREEN).create())) .append(" message", ComponentBuilder.FormatRetention.NONE) .create()) assertMcmlEquals(translate("&8[&a&lInfo&8] &fExample [broadcast](\"&aSupports hover text!\") message"), ComponentBuilder("[").color(ChatColor.DARK_GRAY) .append("Info").bold(true).color(ChatColor.GREEN) .append("] ", ComponentBuilder.FormatRetention.NONE).color(ChatColor.DARK_GRAY) .append("Example ").color(ChatColor.WHITE) .append("broadcast") .event(HoverEvent(HoverEvent.Action.SHOW_TEXT, ComponentBuilder("Supports hover text!") .color(ChatColor.GREEN).create())) .append(" message", ComponentBuilder.FormatRetention.NONE) .create()) assertMcmlEquals(translate("&8[&a&lInfo&8\\] &fExample [broadcast](\"&aSupports hover text!\") message"), ComponentBuilder("Info").bold(true).color(ChatColor.GREEN) .event(HoverEvent(HoverEvent.Action.SHOW_TEXT, ComponentBuilder("Supports hover text!") .color(ChatColor.GREEN).create())) .append("] ", ComponentBuilder.FormatRetention.EVENTS).color(ChatColor.DARK_GRAY) .append("Example [broadcast").color(ChatColor.WHITE) .append(" message", ComponentBuilder.FormatRetention.NONE) .create()) assertMcmlEquals(translate("&8This is a [&freplacement test](\"&a{TEXT}\")"), ComponentBuilder("This is a ").color(ChatColor.DARK_GRAY) .append("replacement test").color(ChatColor.WHITE) .event(HoverEvent(HoverEvent.Action.SHOW_TEXT, ComponentBuilder("\"Hello World!\"") .color(ChatColor.GREEN).create())) .create(), mapOf("{TEXT}" to "\"Hello World!\"")) assertMcmlEquals(translate("&8This is a [&freplacement test](\"&a{TEXT}\")"), ComponentBuilder("This is a ").color(ChatColor.DARK_GRAY) .append("replacement test").color(ChatColor.WHITE) .event(HoverEvent(HoverEvent.Action.SHOW_TEXT, ComponentBuilder("Hey") .color(ChatColor.GREEN).create())) .create(), mapOf("{TEXT}" to "Hey")) assertMcmlEquals(translate("&8This is a [&freplacement test](\"&a{TEXT} {TEXT2}\")"), ComponentBuilder("This is a ").color(ChatColor.DARK_GRAY) .append("replacement test").color(ChatColor.WHITE) .event(HoverEvent(HoverEvent.Action.SHOW_TEXT, ComponentBuilder("Hello World! Hey") .color(ChatColor.GREEN).create())) .create(), mapOf("{TEXT}" to "Hello World!", "{TEXT2}" to "Hey")) assertMcmlEquals(translate("&8This is a [&freplacement test](\"&a{TEXT} {TEXT2}\")"), ComponentBuilder("This is a ").color(ChatColor.DARK_GRAY) .append("replacement test").color(ChatColor.WHITE) .event(HoverEvent(HoverEvent.Action.SHOW_TEXT, ComponentBuilder("Hey Hello World!") .color(ChatColor.GREEN).create())) .create(), mapOf("{TEXT}" to "Hey", "{TEXT2}" to "Hello World!")) } }
apache-2.0
3ac17db4a8d52f1dab93f2522bf50458
55.493724
160
0.596919
4.492845
false
true
false
false
GunoH/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/loopToCallChain/baseTransformations.kt
3
6120
// 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.loopToCallChain import org.jetbrains.kotlin.idea.base.fe10.codeInsight.newDeclaration.Fe10KotlinNameSuggester import org.jetbrains.kotlin.idea.base.psi.copied import org.jetbrains.kotlin.idea.base.psi.replaced import org.jetbrains.kotlin.idea.util.getResolutionScope import org.jetbrains.kotlin.incremental.components.NoLookupLocation import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.PsiChildRange import org.jetbrains.kotlin.resolve.scopes.utils.findClassifier import org.jetbrains.kotlin.resolve.scopes.utils.findFunction import org.jetbrains.kotlin.resolve.scopes.utils.findPackage import org.jetbrains.kotlin.resolve.scopes.utils.findVariable /** * Base class for [ResultTransformation]'s that replaces the loop-expression with the result call chain */ abstract class ReplaceLoopResultTransformation(final override val loop: KtForExpression) : ResultTransformation { override val commentSavingRange = PsiChildRange.singleElement(loop.unwrapIfLabeled()) override fun generateExpressionToReplaceLoopAndCheckErrors(resultCallChain: KtExpression): KtExpression { return resultCallChain } override fun convertLoop(resultCallChain: KtExpression, commentSavingRangeHolder: CommentSavingRangeHolder): KtExpression { return loop.unwrapIfLabeled().replaced(resultCallChain) } } /** * Base class for [ResultTransformation]'s that replaces initialization of a variable with the result call chain */ abstract class AssignToVariableResultTransformation( final override val loop: KtForExpression, protected val initialization: VariableInitialization ) : ResultTransformation { override val commentSavingRange = PsiChildRange(initialization.initializationStatement, loop.unwrapIfLabeled()) override fun generateExpressionToReplaceLoopAndCheckErrors(resultCallChain: KtExpression): KtExpression { val psiFactory = KtPsiFactory(resultCallChain) val initializationStatement = initialization.initializationStatement return if (initializationStatement is KtVariableDeclaration) { val resolutionScope = loop.getResolutionScope() fun isUniqueName(name: String): Boolean { val identifier = Name.identifier(name) return resolutionScope.findVariable(identifier, NoLookupLocation.FROM_IDE) == null && resolutionScope.findFunction(identifier, NoLookupLocation.FROM_IDE) == null && resolutionScope.findClassifier(identifier, NoLookupLocation.FROM_IDE) == null && resolutionScope.findPackage(identifier) == null } val uniqueName = Fe10KotlinNameSuggester.suggestNameByName("test", ::isUniqueName) val copy = initializationStatement.copied() copy.initializer!!.replace(resultCallChain) copy.setName(uniqueName) copy } else { psiFactory.createExpressionByPattern("$0 = $1", initialization.variable.nameAsSafeName, resultCallChain, reformat = false) } } override fun convertLoop(resultCallChain: KtExpression, commentSavingRangeHolder: CommentSavingRangeHolder): KtExpression { initialization.initializer.replace(resultCallChain) val variable = initialization.variable if (variable.isVar && variable.countWriteUsages() == variable.countWriteUsages(loop)) { // change variable to 'val' if possible variable.valOrVarKeyword.replace(KtPsiFactory(variable).createValKeyword()) } val loopUnwrapped = loop.unwrapIfLabeled() // move initializer to the loop if needed var initializationStatement = initialization.initializationStatement if (initializationStatement.nextStatement() != loopUnwrapped) { val block = loopUnwrapped.parent assert(block is KtBlockExpression) val movedInitializationStatement = block.addBefore(initializationStatement, loopUnwrapped) as KtExpression block.addBefore(KtPsiFactory(block).createNewLine(), loopUnwrapped) commentSavingRangeHolder.remove(initializationStatement) initializationStatement.delete() initializationStatement = movedInitializationStatement } loopUnwrapped.delete() return initializationStatement } companion object { fun createDelegated(delegate: ResultTransformation, initialization: VariableInitialization): AssignToVariableResultTransformation { return object : AssignToVariableResultTransformation(delegate.loop, initialization) { override val presentation: String get() = delegate.presentation override fun generateCode(chainedCallGenerator: ChainedCallGenerator): KtExpression { return delegate.generateCode(chainedCallGenerator) } override val lazyMakesSense: Boolean get() = delegate.lazyMakesSense } } } } /** * [ResultTransformation] that replaces initialization of a variable with the call chain produced by the given [SequenceTransformation] */ class AssignSequenceResultTransformation( private val sequenceTransformation: SequenceTransformation, initialization: VariableInitialization ) : AssignToVariableResultTransformation(sequenceTransformation.loop, initialization) { override val presentation: String get() = sequenceTransformation.presentation override fun buildPresentation(prevTransformationsPresentation: String?): String { return sequenceTransformation.buildPresentation(prevTransformationsPresentation) } override fun generateCode(chainedCallGenerator: ChainedCallGenerator): KtExpression { return sequenceTransformation.generateCode(chainedCallGenerator) } }
apache-2.0
ffe6fce4348aeaf1326df459c4fae9c4
45.022556
158
0.74232
5.735708
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/ToRawStringLiteralIntention.kt
2
3707
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.intentions import com.intellij.codeInsight.intention.LowPriorityAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.util.text.StringUtilRt import com.intellij.psi.PsiErrorElement import com.intellij.psi.util.PsiTreeUtil import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.core.replaced import org.jetbrains.kotlin.psi.KtEscapeStringTemplateEntry import org.jetbrains.kotlin.psi.KtPsiFactory import org.jetbrains.kotlin.psi.KtStringTemplateEntry import org.jetbrains.kotlin.psi.KtStringTemplateExpression import org.jetbrains.kotlin.psi.psiUtil.endOffset import org.jetbrains.kotlin.psi.psiUtil.startOffset class ToRawStringLiteralIntention : SelfTargetingOffsetIndependentIntention<KtStringTemplateExpression>( KtStringTemplateExpression::class.java, KotlinBundle.lazyMessage("to.raw.string.literal") ), LowPriorityAction { override fun isApplicableTo(element: KtStringTemplateExpression): Boolean { if (PsiTreeUtil.nextLeaf(element) is PsiErrorElement) { // Parse error right after the literal // the replacement may make things even worse, suppress the action return false } val text = element.text if (text.startsWith("\"\"\"")) return false // already raw val escapeEntries = element.entries.filterIsInstance<KtEscapeStringTemplateEntry>() for (entry in escapeEntries) { val c = entry.unescapedValue.singleOrNull() ?: return false if (Character.isISOControl(c) && c != '\n' && c != '\r') return false } val converted = convertContent(element) return !converted.contains("\"\"\"") && !hasTrailingSpaces(converted) } override fun applyTo(element: KtStringTemplateExpression, editor: Editor?) { val startOffset = element.startOffset val endOffset = element.endOffset val currentOffset = editor?.caretModel?.currentCaret?.offset ?: startOffset val text = convertContent(element) val replaced = element.replaced(KtPsiFactory(element).createExpression("\"\"\"" + text + "\"\"\"")) val offset = when { startOffset == currentOffset -> startOffset endOffset == currentOffset -> replaced.endOffset else -> minOf(currentOffset + 2, replaced.endOffset) } editor?.caretModel?.moveToOffset(offset) } private fun convertContent(element: KtStringTemplateExpression): String { val text = buildString { val entries = element.entries for ((index, entry) in entries.withIndex()) { val value = entry.value() if (value.endsWith("$") && index < entries.size - 1) { val nextChar = entries[index + 1].value().first() if (nextChar.isJavaIdentifierStart() || nextChar == '{') { append("\${\"$\"}") continue } } append(value) } } return StringUtilRt.convertLineSeparators(text, "\n") } private fun hasTrailingSpaces(text: String): Boolean { var afterSpace = false for (c in text) { if ((c == '\n' || c == '\r') && afterSpace) return true afterSpace = c == ' ' || c == '\t' } return false } private fun KtStringTemplateEntry.value() = if (this is KtEscapeStringTemplateEntry) this.unescapedValue else text }
apache-2.0
95c4ed00c431491dc5e094d286407754
39.747253
158
0.654168
5.078082
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/AddFunctionToSupertypeFix.kt
1
9310
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.quickfix import com.intellij.codeInsight.intention.IntentionAction import com.intellij.codeInsight.intention.LowPriorityAction import com.intellij.openapi.command.CommandProcessor import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.openapi.ui.popup.JBPopupFactory import com.intellij.openapi.ui.popup.ListPopupStep import com.intellij.openapi.ui.popup.PopupStep import com.intellij.openapi.ui.popup.util.BaseListPopupStep import com.intellij.util.PlatformIcons import org.jetbrains.annotations.Nls import org.jetbrains.kotlin.builtins.KotlinBuiltIns import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny import org.jetbrains.kotlin.idea.codeInsight.DescriptorToSourceUtilsIde import org.jetbrains.kotlin.idea.core.ShortenReferences import org.jetbrains.kotlin.idea.core.TemplateKind import org.jetbrains.kotlin.idea.core.getFunctionBodyTextFromTemplate import org.jetbrains.kotlin.idea.core.implicitModality import org.jetbrains.kotlin.idea.imports.importableFqName import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers import org.jetbrains.kotlin.idea.util.application.executeWriteCommand import org.jetbrains.kotlin.lexer.KtModifierKeywordToken import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.modalityModifier import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.types.checker.KotlinTypeChecker import org.jetbrains.kotlin.types.typeUtil.supertypes class AddFunctionToSupertypeFix private constructor( element: KtNamedFunction, private val functions: List<FunctionData> ) : KotlinQuickFixAction<KtNamedFunction>(element), LowPriorityAction { init { assert(functions.isNotEmpty()) } private class FunctionData( val signaturePreview: String, val sourceCode: String, val targetClass: KtClass ) override fun getText(): String = functions.singleOrNull()?.let { actionName(it) } ?: KotlinBundle.message("fix.add.function.supertype.text") override fun getFamilyName() = KotlinBundle.message("fix.add.function.supertype.family") override fun startInWriteAction(): Boolean = false override fun invoke(project: Project, editor: Editor?, file: KtFile) { CommandProcessor.getInstance().runUndoTransparentAction { if (functions.size == 1 || editor == null || !editor.component.isShowing) { addFunction(functions.first(), project) } else { JBPopupFactory.getInstance().createListPopup(createFunctionPopup(project)).showInBestPositionFor(editor) } } } private fun addFunction(functionData: FunctionData, project: Project) { project.executeWriteCommand(KotlinBundle.message("fix.add.function.supertype.progress")) { val classBody = functionData.targetClass.getOrCreateBody() val functionElement = KtPsiFactory(project).createFunction(functionData.sourceCode) val insertedFunctionElement = classBody.addBefore(functionElement, classBody.rBrace) as KtNamedFunction ShortenReferences.DEFAULT.process(insertedFunctionElement) val modifierToken = insertedFunctionElement.modalityModifier()?.node?.elementType as? KtModifierKeywordToken ?: return@executeWriteCommand if (insertedFunctionElement.implicitModality() == modifierToken) { RemoveModifierFix(insertedFunctionElement, modifierToken, true).invoke() } } } private fun createFunctionPopup(project: Project): ListPopupStep<*> { return object : BaseListPopupStep<FunctionData>(KotlinBundle.message("fix.add.function.supertype.choose.type"), functions) { override fun isAutoSelectionEnabled() = false override fun onChosen(selectedValue: FunctionData, finalChoice: Boolean): PopupStep<*>? { if (finalChoice) { addFunction(selectedValue, project) } return PopupStep.FINAL_CHOICE } override fun getIconFor(value: FunctionData) = PlatformIcons.FUNCTION_ICON override fun getTextFor(value: FunctionData) = actionName(value) } } @Nls private fun actionName(functionData: FunctionData): String = KotlinBundle.message( "fix.add.function.supertype.add.to", functionData.signaturePreview, functionData.targetClass.name.toString() ) companion object : KotlinSingleIntentionActionFactory() { override fun createAction(diagnostic: Diagnostic): IntentionAction? { val function = diagnostic.psiElement as? KtNamedFunction ?: return null val descriptors = generateFunctionsToAdd(function) if (descriptors.isEmpty()) return null val project = diagnostic.psiFile.project val functionData = descriptors.mapNotNull { createFunctionData(it, project) } if (functionData.isEmpty()) return null return AddFunctionToSupertypeFix(function, functionData) } private fun createFunctionData(functionDescriptor: FunctionDescriptor, project: Project): FunctionData? { val classDescriptor = functionDescriptor.containingDeclaration as ClassDescriptor var sourceCode = IdeDescriptorRenderers.SOURCE_CODE.render(functionDescriptor) if (classDescriptor.kind != ClassKind.INTERFACE && functionDescriptor.modality != Modality.ABSTRACT) { val returnType = functionDescriptor.returnType sourceCode += if (returnType == null || !KotlinBuiltIns.isUnit(returnType)) { val bodyText = getFunctionBodyTextFromTemplate( project, TemplateKind.FUNCTION, functionDescriptor.name.asString(), functionDescriptor.returnType?.let { IdeDescriptorRenderers.SOURCE_CODE.renderType(it) } ?: "Unit", classDescriptor.importableFqName ) "{\n$bodyText\n}" } else { "{}" } } val targetClass = DescriptorToSourceUtilsIde.getAnyDeclaration(project, classDescriptor) as? KtClass ?: return null return FunctionData( IdeDescriptorRenderers.SOURCE_CODE_SHORT_NAMES_NO_ANNOTATIONS.render(functionDescriptor), sourceCode, targetClass ) } private fun generateFunctionsToAdd(functionElement: KtNamedFunction): List<FunctionDescriptor> { val functionDescriptor = functionElement.resolveToDescriptorIfAny(BodyResolveMode.FULL) ?: return emptyList() val containingClass = functionDescriptor.containingDeclaration as? ClassDescriptor ?: return emptyList() // TODO: filter out impossible supertypes (for example when argument's type isn't visible in a superclass). return getSuperClasses(containingClass) .asSequence() .filterNot { KotlinBuiltIns.isAnyOrNullableAny(it.defaultType) } .map { generateFunctionSignatureForType(functionDescriptor, it) } .toList() } private fun MutableList<KotlinType>.sortSubtypesFirst(): List<KotlinType> { val typeChecker = KotlinTypeChecker.DEFAULT for (i in 1 until size) { val currentType = this[i] for (j in 0 until i) { if (typeChecker.isSubtypeOf(currentType, this[j])) { this.removeAt(i) this.add(j, currentType) break } } } return this } private fun getSuperClasses(classDescriptor: ClassDescriptor): List<ClassDescriptor> { val supertypes = classDescriptor.defaultType.supertypes().toMutableList().sortSubtypesFirst() return supertypes.mapNotNull { it.constructor.declarationDescriptor as? ClassDescriptor } } private fun generateFunctionSignatureForType( functionDescriptor: FunctionDescriptor, typeDescriptor: ClassDescriptor ): FunctionDescriptor { // TODO: support for generics. val modality = if (typeDescriptor.kind == ClassKind.INTERFACE || typeDescriptor.modality == Modality.SEALED) { Modality.ABSTRACT } else { typeDescriptor.modality } return functionDescriptor.copy( typeDescriptor, modality, functionDescriptor.visibility, CallableMemberDescriptor.Kind.DECLARATION, /* copyOverrides = */ false ) } } }
apache-2.0
5ab93114e9577739c5486bc34c60d789
44.637255
158
0.677873
5.581535
false
false
false
false
simonnorberg/dmach
app/src/main/java/net/simno/dmach/core/TextButton.kt
1
1985
package net.simno.dmach.core import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.interaction.collectIsPressedAsState import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.padding import androidx.compose.material3.MaterialTheme import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.semantics.Role @Composable fun TextButton( text: String, selected: Boolean, modifier: Modifier = Modifier, enabled: Boolean = true, radioButton: Boolean = false, textPadding: PaddingValues = PaddingValues(), onClick: () -> Unit ) { val interactionSource = remember { MutableInteractionSource() } val pressed by interactionSource.collectIsPressedAsState() val background = when { !enabled -> MaterialTheme.colorScheme.surface selected && radioButton -> MaterialTheme.colorScheme.secondary pressed -> MaterialTheme.colorScheme.onSecondary selected -> MaterialTheme.colorScheme.secondary else -> MaterialTheme.colorScheme.primary } Box( modifier = modifier .background( color = background, shape = MaterialTheme.shapes.small ) .clickable( onClick = onClick, enabled = enabled, role = Role.Button, interactionSource = interactionSource, indication = null ), contentAlignment = Alignment.Center ) { LightMediumText( text = text.uppercase(), modifier = Modifier.padding(textPadding) ) } }
gpl-3.0
8e1e5d53722df15eb74e7285804a8447
33.824561
71
0.695718
5.293333
false
false
false
false
joaomneto/TitanCompanion
src/main/java/pt/joaomneto/titancompanion/adventure/impl/POFAdventure.kt
1
2581
package pt.joaomneto.titancompanion.adventure.impl import android.os.Bundle import android.view.Menu import java.io.BufferedWriter import java.io.IOException import pt.joaomneto.titancompanion.R import pt.joaomneto.titancompanion.adventure.Adventure import pt.joaomneto.titancompanion.adventure.impl.fragments.AdventureCombatFragment import pt.joaomneto.titancompanion.adventure.impl.fragments.AdventureEquipmentFragment import pt.joaomneto.titancompanion.adventure.impl.fragments.AdventureNotesFragment import pt.joaomneto.titancompanion.adventure.impl.fragments.pof.POFAdventureVitalStatsFragment import pt.joaomneto.titancompanion.util.AdventureFragmentRunner class POFAdventure : Adventure( arrayOf( AdventureFragmentRunner(R.string.vitalStats, POFAdventureVitalStatsFragment::class), AdventureFragmentRunner(R.string.fights, AdventureCombatFragment::class), AdventureFragmentRunner(R.string.goldEquipment, AdventureEquipmentFragment::class), AdventureFragmentRunner(R.string.notes, AdventureNotesFragment::class) ) ) { var currentPower = -1 var initialPower = -1 override fun onCreate(savedInstanceState: Bundle?) { try { super.onCreate(savedInstanceState) } catch (e: Exception) { e.printStackTrace() } } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.adventure, menu) return true } @Throws(IOException::class) override fun storeAdventureSpecificValuesInFile(bw: BufferedWriter) { bw.write("currentPower=" + currentPower + "\n") bw.write("initialPower=" + initialPower + "\n") bw.write("standardPotion=" + standardPotion + "\n") bw.write("standardPotionValue=" + standardPotionValue + "\n") bw.write("provisions=0\n") bw.write("provisionsValue=4\n") bw.write("gold=" + gold + "\n") } override fun loadAdventureSpecificValuesFromFile() { standardPotion = Integer.valueOf( savedGame .getProperty("standardPotion") ) standardPotionValue = Integer.valueOf( savedGame .getProperty("standardPotionValue") ) gold = Integer.valueOf(savedGame.getProperty("gold")) currentPower = Integer.valueOf(savedGame.getProperty("currentPower")) initialPower = Integer.valueOf(savedGame.getProperty("initialPower")) } companion object { protected val FRAGMENT_EQUIPMENT = 2 protected val FRAGMENT_NOTES = 3 } }
lgpl-3.0
ab5f94b8d58e42932006e42a26099181
36.405797
94
0.708253
4.642086
false
false
false
false
gatling/gatling
src/docs/content/tutorials/advanced/code/AdvancedTutorialSampleKotlin.kt
1
3031
/* * Copyright 2011-2021 GatlingCorp (https://gatling.io) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import io.gatling.javaapi.core.* import io.gatling.javaapi.core.CoreDsl.* import io.gatling.javaapi.http.HttpDsl.* class AdvancedTutorialSampleKotlin { object Step1 : Simulation() { //#isolate-processes val search = // let's give proper names, as they are displayed in the reports exec(http("Home") .get("/")) .pause(7) .exec(http("Search") .get("/computers?f=macbook")) .pause(2) .exec(http("Select") .get("/computers/6")) .pause(3) val browse: ChainBuilder = TODO() val edit: ChainBuilder = TODO() //#isolate-processes //#processes val scn = scenario("Scenario Name") .exec(search, browse, edit) //#processes //#populations val users = scenario("Users") .exec(search, browse) val admins = scenario("Admins") .exec(search, browse, edit) //#populations val httpProtocol = http //#setup-users init { setUp(users.injectOpen(atOnceUsers(10)).protocols(httpProtocol)) } //#setup-users //#setup-users-and-admins init { setUp( users.injectOpen(rampUsers(10).during(10)), admins.injectOpen(rampUsers(2).during(10)) ).protocols(httpProtocol) } //#setup-users-and-admins } } //#feeder val feeder = csv("search.csv").random() // 1, 2 val search = exec(http("Home") .get("/")) .pause(1) .feed(feeder) // 3 .exec(http("Search") .get("/computers?f=#{searchCriterion}") // 4 .check( css("a:contains('#{searchComputerName}')", "href") // 5 .saveAs("computerUrl") ) ) .pause(1) .exec(http("Select") .get("#{computerUrl}")) // 6 .pause(1) //#feeder object BrowseLoopSimple { //#loop-simple fun gotoPage(page: Int) = exec(http("Page $page") .get("/computers?p=$page")) .pause(1) val browse = exec( gotoPage(0), gotoPage(1), gotoPage(2), gotoPage(3), gotoPage(4) ) //#loop-simple } object BrowseLoopFor { //#loop-for val browse = repeat(5, "n").on( // 1 exec(http("Page #{n}").get("/computers?p=#{n}")) // 2 .pause(1) ) //#loop-for } object CheckAndTryMax { //#check val edit = exec(http("Form").get("/computers/new")) .pause(1) .exec(http("Post") .post("/computers") .check(status().shouldBe { session -> 200 + java.util.concurrent.ThreadLocalRandom.current().nextInt(2) }) ) //#check //#tryMax-exitHereIfFailed val tryMaxEdit = tryMax(2).on( // 1 exec(edit) ).exitHereIfFailed() // 2 //#tryMax-exitHereIfFailed }
apache-2.0
de9b7b7d47bf6dd0e198f79ccb3a9d40
20.805755
75
0.649291
3.224468
false
false
false
false
prof18/RSS-Parser
rssparser/src/test/java/com/prof/rssparser/core/CoreXMLParserFirstLineEmptyTest.kt
1
9907
/* * Copyright 2020 Marco Gomiero * * 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.prof.rssparser.core import com.prof.rssparser.Article import com.prof.rssparser.Channel import org.junit.Assert.assertEquals import org.junit.Assert.assertNull import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner @RunWith(RobolectricTestRunner::class) class CoreXMLParserFirstLineEmptyTest { private lateinit var articleList: List<Article> private lateinit var article: Article private val feedPath = "/feed-test-first-line-blank.xml" private lateinit var channel: Channel @Before fun setUp() { val inputStream = javaClass.getResourceAsStream(feedPath)!! val feed = inputStream.bufferedReader().use { it.readText() } channel = CoreXMLParser.parseXML(feed) articleList = channel.articles article = articleList[0] } @Test fun channelTitle_isCorrect() { assertEquals("Inteligência artificial – Portal CNJ", channel.title) } @Test fun channelDesc_isCorrect() { assertEquals("Conselho Nacional de Justiça", channel.description) } @Test fun channelLink_isCorrect() { assertEquals("https://www.cnj.jus.br", channel.link) } @Test fun channelImage_isNull() { assertEquals( "https://www.cnj.jus.br/wp-content/uploads/2020/06/Favicons-Portal-CNJ-1-36x36.jpg", channel.image!!.url ) } @Test fun channelLastBuild_isCorrect() { assertEquals("Fri, 07 Aug 2020 14:03:42 +0000", channel.lastBuildDate) } @Test fun channelUpdatePeriod_isCorrect() { assertEquals("hourly", channel.updatePeriod) } @Test @Throws fun size_isCorrect() { assertEquals(9, articleList.size) } @Test @Throws fun title_isCorrect() { assertEquals("TJ é premiado em evento nacional sobre inovação e direito para o ecossistema", article.title) } @Test @Throws fun author_isCorrect() { assertEquals("Marcio Gonçalves", article.author) } @Test @Throws fun link_isCorrect() { assertEquals( "https://www.cnj.jus.br/tj-e-premiado-em-evento-nacional-sobre-inovacao-e-direito-para-o-ecossistema/?utm_source=rss&utm_medium=rss&utm_campaign=tj-e-premiado-em-evento-nacional-sobre-inovacao-e-direito-para-o-ecossistema", article.link ) } @Test @Throws fun pubDate_isCorrect() { assertEquals("Thu, 18 Jun 2020 22:37:47 +0000", article.pubDate) } @Test @Throws fun description_isCorrect() { assertEquals( "<p>O Tribunal de Justiça de Mato Grosso (TJMT) recebeu o prêmio destaque do Expojud online, Congresso de Inovação, Tecnologia e Direito para o Ecossistema da Justiça realizado de dois a quatro de junho. O Judiciário estadual foi condecorado na categoria Maior Participação de Instituição de Justiça. “Esse reconhecimento mostra que estamos no melhor caminho e [&#8230;]</p>\n" + "<p>The post <a rel=\"nofollow\" href=\"https://www.cnj.jus.br/tj-e-premiado-em-evento-nacional-sobre-inovacao-e-direito-para-o-ecossistema/\">TJ é premiado em evento nacional sobre inovação e direito para o ecossistema</a> appeared first on <a rel=\"nofollow\" href=\"https://www.cnj.jus.br\">Portal CNJ</a>.</p>", article.description ) } @Test @Throws fun content_isCorrect() { assertEquals( "<p>O Tribunal de Justiça de Mato Grosso (TJMT) recebeu o prêmio destaque do Expojud online, Congresso de Inovação, Tecnologia e Direito para o Ecossistema da Justiça realizado de dois a quatro de junho. O Judiciário estadual foi condecorado na categoria Maior Participação de Instituição de Justiça. “Esse reconhecimento mostra que estamos no melhor caminho e certifica o trabalho que vem sendo desenvolvido no nosso tribunal. Tudo isso é fruto dos investimentos e do planejamento estratégico traçado de forma contundente na administração do desembargador Carlos Alberto Alves da Rocha”, frisa Luiz Octávio Oliveira Sabóia Ribeiro, juiz auxiliar da Presidência do TJMT.</p>\n" + "<p>O evento, 100% virtual, transmitido via YouTube, reuniu mais de cinco mil magistrados, servidores, profissionais de Tecnologia da Informação e operadores do Direito das instituições do sistema judicial de todos os estados. Durante os três dias, sempre no período matutino, os participantes tiveram a oportunidade de fazer interações com os palestrantes e visitas aos stands virtuais de instituições do Judiciário e das empresas apoiadoras do congresso. E o TJMT estava entre as 23 instituições que apresentaram inovações tecnológicas a serviço da qualidade da prestação jurisdicional.</p>\n" + "<p>Foram promovidas mais de 50 palestras, distribuídas entre dois palcos virtuais, com especialistas de diversos setores que falaram sobre inovação, tecnologia, casos de sucesso e empreendedorismo dentro do sistema judicial. Os temas foram aplicados à realidade atual do Judiciário, como os cenários pós-pandemia e o impacto na Justiça, os efeitos da pandemia nas atividades dos magistrados, Covid-19 e os impactos dessas complexidades na revolução tecnológica nos tribunais superiores. Também foi debatida a importância do alinhamento da estratégia digital com a estratégia de negócio nos tribunais.</p>\n" + "<p>Na programação, os conteúdos de tecnologia proporcionaram uma imersão nas soluções que estão transformando os tribunais de Justiça, entre os temas centrais estavam inteligência artificial (IA), plataformas de colaboração em vídeo, machine learning, realidade virtual, blockchain e as soluções que envolvem todas as esferas da Lei Geral de Proteção de Dados Pessoais.</p>\n" + "<p>E como inteligência artificial figurava entre os assuntos de maior centralidade do seminário, o juiz federal Pedro Felipe Santos abordou como a pandemia do novo coronavírus possibilitou a aceleração da implementação de novas ferramentas digitais na prestação jurisdicional, além de como essa aceleração provocou transformações que influenciaram os serviços que hoje são prestados à sociedade.</p>\n" + "<p>No entanto, o magistrado federal demonstrou preocupação com essa aceleração e ressaltou “a necessidade da observação das medidas éticas e cautelares no desenvolvimento da inteligência artificial no Judiciário brasileiro”. Segundo Pedro Felipe, essa experiência pode e deve ser positiva, justamente porque todos estão empenhados em desenvolver e trocar experiências acerca do tema, uma vez que, na avaliação dele, a inteligência artificial multiplica os cérebros pensando a Justiça brasileira.</p>\n" + "<p>O juiz Pedro Felipe também se mostrou otimista em relação ao desenvolvimento de IA pelo Poder Judiciário brasileiro, e reiterou a necessidade de observação de questões éticas e afirmou ser fundamental a criação de um marco regulatório para utilização desse tipo de tecnologia.</p>\n" + "<p>Na visão do ativista em inovação e curador do congresso, advogado Ademir Piccoli, o evento superou todas as expectativas. Nos cálculos dele, alguns painéis contaram com até 1.400 pessoas conectadas simultaneamente. “Foi surpreendente, e o Tribunal de Justiça de Mato Grosso está de parabéns. Mostrou que está atento às inovações, e essa estratégia é muito importante. Além disso, foi um dos quatro tribunais que participou com o maior número de inscritos”, sinalizou Piccoli.</p>\n" + "<p style=\"text-align: right;\"><em>Fonte: <a href=\"http://www.tjmt.jus.br/noticias/59610#.XuvrKmhKjIU\" target=\"_blank\" rel=\"noopener noreferrer\">TJMT</a></em></p>\n" + "<p>The post <a rel=\"nofollow\" href=\"https://www.cnj.jus.br/tj-e-premiado-em-evento-nacional-sobre-inovacao-e-direito-para-o-ecossistema/\">TJ é premiado em evento nacional sobre inovação e direito para o ecossistema</a> appeared first on <a rel=\"nofollow\" href=\"https://www.cnj.jus.br\">Portal CNJ</a>.</p>", article.content ) } @Test @Throws fun image_isCorrect() { assertNull(article.image) } @Test @Throws fun categories_isCorrect() { assertEquals( mutableListOf( "Notícias do Judiciário", "Agência CNJ de Notícias", "tecnologia e modernização", "TJMT", "tecnologia da informação", "Inteligência artificial", "coronavirus", ), article.categories ) } @Test @Throws fun guid_isCorrect() { assertEquals("https://www.cnj.jus.br/?p=109151", article.guid) } @Test @Throws fun audio_iCorrect() { assertNull(article.audio) } @Test @Throws fun sourceName_iCorrect() { assertNull(article.sourceName) } @Test @Throws fun sourceUrl_iCorrect() { assertNull(article.sourceUrl) } @Test @Throws fun video_isCorrect() { assertNull(article.video) } }
apache-2.0
fb6674d39316562d9ea5ab2a5153af87
50.189474
691
0.70982
3.138109
false
true
false
false
morizooo/conference2017-android
app/src/main/kotlin/io/builderscon/conference2017/view/activity/MainActivity.kt
1
2877
package io.builderscon.conference2017.view.activity import android.os.Bundle import android.support.design.internal.BottomNavigationMenuView import android.support.design.widget.BottomNavigationView import android.support.v7.app.AppCompatActivity import android.util.TypedValue import android.view.View import io.builderscon.conference2017.R import io.builderscon.conference2017.extension.initSupportActionBar import io.builderscon.conference2017.view.fragment.InformationFragment import io.builderscon.conference2017.view.fragment.TimetableFragment import kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity() { private val informationItemId = R.id.navigation_information private val timelineItemId = R.id.navigation_timeline override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) initSupportActionBar(tool_bar) navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener) navigation.selectedItemId = timelineItemId changeIconSize() } private val mOnNavigationItemSelectedListener = BottomNavigationView.OnNavigationItemSelectedListener { item -> when (item.itemId) { timelineItemId -> { toolbar_title.text = getString(R.string.title_timetable) val fragmentManager = supportFragmentManager var fragment = fragmentManager.findFragmentByTag("TimetableFragment") if (fragment == null) { fragment = TimetableFragment() } this.supportFragmentManager.beginTransaction().replace(R.id.fragment, fragment, "TimetableFragment").commit() return@OnNavigationItemSelectedListener true } informationItemId -> { toolbar_title.text = getString(R.string.title_information) this.supportFragmentManager.beginTransaction().replace(R.id.fragment, InformationFragment(), "InformationFragment").commit() return@OnNavigationItemSelectedListener true } } false } private fun changeIconSize() { val menuView = navigation.getChildAt(0) as BottomNavigationMenuView for (i in 0..menuView.childCount - 1) { val iconView = menuView.getChildAt(i).findViewById<View>(android.support.design.R.id.icon) val displayMetrics = resources.displayMetrics val layoutParams = iconView.layoutParams.apply { height = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 30f, displayMetrics).toInt() width = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 30f, displayMetrics).toInt() } iconView.layoutParams = layoutParams } } }
apache-2.0
c8cb1774599e27ca628e6485b2adaedf
43.953125
140
0.706639
5.407895
false
false
false
false
square/sqldelight
sqldelight-idea-plugin/src/main/kotlin/com/squareup/sqldelight/intellij/actions/GenerateInsertIntoQueryAction.kt
1
1392
package com.squareup.sqldelight.intellij.actions import com.alecstrong.sql.psi.core.psi.SqlCreateTableStmt import com.intellij.codeInsight.CodeInsightActionHandler import com.intellij.codeInsight.template.TemplateManager import com.intellij.codeInsight.template.impl.TemplateManagerImpl import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.PsiFile import com.intellij.psi.util.parentOfType import com.squareup.sqldelight.core.lang.util.findChildOfType import com.squareup.sqldelight.core.psi.SqlDelightStmtList internal class GenerateInsertIntoQueryAction : BaseGenerateAction(InsertIntoHandler()) { class InsertIntoHandler : CodeInsightActionHandler { override fun invoke(project: Project, editor: Editor, file: PsiFile) { val caretOffset = editor.caretModel.offset val createTableStmt = file.findElementAt(caretOffset)?.parentOfType<SqlCreateTableStmt>() ?: return val tableName = createTableStmt.tableName.name val template = TemplateManagerImpl.listApplicableTemplates(file, caretOffset, false) .first { it.key == "ins" } val stmtList = file.findChildOfType<SqlDelightStmtList>() ?: return insertNewLineAndCleanup(editor, stmtList) TemplateManager.getInstance(project).startTemplate( editor, template, false, mapOf("table" to tableName), null ) } } }
apache-2.0
8e64687fdd647b4afe7bcf571f65d6e4
43.903226
105
0.79023
4.64
false
false
false
false
virvar/magnetic-ball-2
MagneticBallLogic/src/main/kotlin/ru/virvar/apps/magneticBall2/turnHandlers/ImpulseTurnHandler.kt
1
2010
package ru.virvar.apps.magneticBall2.turnHandlers import ru.virvar.apps.magneticBallCore.* import ru.virvar.apps.magneticBall2.blocks.ActiveBlock import ru.virvar.apps.magneticBall2.MagneticBallLevel class ImpulseTurnHandler : ITurnHandler { private var handleBlockCallDepth: Int = 0 private val handleBlockCallDepthMax = 100 override fun turn(level: Level, direction: Point2D) { val player = (level as MagneticBallLevel).player handleBlockCallDepth = 0 handleBlock(level, player, direction) if (!level.blocks.containsKey(player.id)) { level.gameState = GameState.LOOSE } } private fun handleBlock(level: Level, block: Block, direction: Point2D) { handleBlockCallDepth++ if (handleBlockCallDepth > handleBlockCallDepthMax) { return } val newPosition = findFirstBlock(level, block, direction) val firstBlock = if (level.isOutOfField(newPosition)) null else level.getBlock(newPosition.x, newPosition.y)as ActiveBlock? if (firstBlock != null) { val newDirection = firstBlock.blockEnter(level, block, direction) if (!newDirection.isEmpty()) { handleBlock(level, block, newDirection) } } else { // go out of field level.moveHelper.move(level, block, direction, newPosition) } } private fun findFirstBlock(level: Level, from: Block, direction: Point2D): Point2D { val newPosition = Point2D(from.x, from.y) while (newPosition.x >= 0 && newPosition.y >= 0 && newPosition.x < level.fieldSize && newPosition.y < level.fieldSize && ((level.getBlock(newPosition.x, newPosition.y) == null) || (level.getBlock(newPosition.x, newPosition.y) == from))) { newPosition.x += direction.x newPosition.y += direction.y } return newPosition } }
gpl-2.0
44fcc3a91742b59a038312e00a28ddf1
38.372549
131
0.626992
4.290598
false
false
false
false
Esri/arcgis-runtime-samples-android
kotlin/add-features-with-contingent-values/src/main/java/com/esri/arcgisruntime/sample/addfeatureswithcontingentvalues/MainActivity.kt
1
22046
/* Copyright 2022 Esri * * 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.esri.arcgisruntime.sample.addfeatureswithcontingentvalues import android.graphics.Color import android.os.Bundle import android.util.Log import android.view.MotionEvent import android.view.ViewGroup import android.widget.ArrayAdapter import android.widget.AutoCompleteTextView import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import com.esri.arcgisruntime.ArcGISRuntimeEnvironment import com.esri.arcgisruntime.data.ArcGISFeature import com.esri.arcgisruntime.data.ArcGISFeatureTable import com.esri.arcgisruntime.data.CodedValue import com.esri.arcgisruntime.data.CodedValueDomain import com.esri.arcgisruntime.data.ContingentCodedValue import com.esri.arcgisruntime.data.ContingentRangeValue import com.esri.arcgisruntime.data.Feature import com.esri.arcgisruntime.data.Geodatabase import com.esri.arcgisruntime.data.QueryParameters import com.esri.arcgisruntime.geometry.GeometryEngine import com.esri.arcgisruntime.geometry.Point import com.esri.arcgisruntime.layers.ArcGISVectorTiledLayer import com.esri.arcgisruntime.layers.FeatureLayer import com.esri.arcgisruntime.loadable.LoadStatus import com.esri.arcgisruntime.mapping.ArcGISMap import com.esri.arcgisruntime.mapping.Basemap import com.esri.arcgisruntime.mapping.Viewpoint import com.esri.arcgisruntime.mapping.view.DefaultMapViewOnTouchListener import com.esri.arcgisruntime.mapping.view.Graphic import com.esri.arcgisruntime.mapping.view.GraphicsOverlay import com.esri.arcgisruntime.mapping.view.MapView import com.esri.arcgisruntime.sample.addfeatureswithcontingentvalues.databinding.ActivityMainBinding import com.esri.arcgisruntime.sample.addfeatureswithcontingentvalues.databinding.AddFeatureLayoutBinding import com.esri.arcgisruntime.symbology.SimpleFillSymbol import com.esri.arcgisruntime.symbology.SimpleLineSymbol import com.esri.arcgisruntime.symbology.SimpleMarkerSymbol import com.google.android.material.bottomsheet.BottomSheetBehavior import com.google.android.material.bottomsheet.BottomSheetDialog import java.io.File class MainActivity : AppCompatActivity() { private val TAG: String = MainActivity::class.java.simpleName private val activityMainBinding by lazy { ActivityMainBinding.inflate(layoutInflater) } private val bottomSheetBinding by lazy { AddFeatureLayoutBinding.inflate(layoutInflater) } private val mapView: MapView by lazy { activityMainBinding.mapView } // graphic overlay instance to add the feature graphic to the map private val graphicsOverlay = GraphicsOverlay() // mobile database containing offline feature data. GeoDatabase is closed on app exit private var geoDatabase: Geodatabase? = null // instance of the contingent feature to be added to the map private var feature: ArcGISFeature? = null // instance of the feature table retrieved from the GeoDatabase, updates when new feature is added private var featureTable: ArcGISFeatureTable? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(activityMainBinding.root) // authentication with an API key or named user is required to access basemaps and other location services ArcGISRuntimeEnvironment.setApiKey(BuildConfig.API_KEY) // create a temporary directory to use the geodatabase file createGeodatabaseCacheDirectory() // use the offline vector tiled layer as a basemap val fillmoreVectorTiledLayer = ArcGISVectorTiledLayer( getExternalFilesDir(null)?.path + "/FillmoreTopographicMap.vtpk" ) mapView.apply { // set the basemap layer and the graphic overlay to the MapView map = ArcGISMap(Basemap(fillmoreVectorTiledLayer)) graphicsOverlays.add(graphicsOverlay) // add a listener to the MapView to detect when a user has performed a single tap to add a new feature onTouchListener = object : DefaultMapViewOnTouchListener(this@MainActivity, this) { override fun onSingleTapConfirmed(motionEvent: MotionEvent?): Boolean { motionEvent?.let { event -> // create a point from where the user clicked android.graphics.Point(event.x.toInt(), event.y.toInt()).let { point -> // create a map point and add a new feature to the service feature table openBottomSheetView(screenToLocation(point)) } } performClick() return super.onSingleTapConfirmed(motionEvent) } } } // retrieve and load the offline mobile GeoDatabase file from the cache directory geoDatabase = Geodatabase(cacheDir.path + "/ContingentValuesBirdNests.geodatabase") geoDatabase?.loadAsync() geoDatabase?.addDoneLoadingListener { if (geoDatabase?.loadStatus == LoadStatus.LOADED) { (geoDatabase?.geodatabaseFeatureTables?.first() as? ArcGISFeatureTable)?.let { featureTable -> this.featureTable = featureTable featureTable.loadAsync() featureTable.addDoneLoadingListener { // create and load the feature layer from the feature table val featureLayer = FeatureLayer(featureTable) // add the feature layer to the map mapView.map.operationalLayers.add(featureLayer) // set the map's viewpoint to the feature layer's full extent val extent = featureLayer.fullExtent mapView.setViewpoint(Viewpoint(extent)) // add buffer graphics for the feature layer queryFeatures() } } } else { val error = "Error loading GeoDatabase: " + geoDatabase?.loadError?.message Toast.makeText(this, error, Toast.LENGTH_SHORT).show() Log.e(TAG, error) } } } /** * Geodatabase creates and uses various temporary files while processing a database, * which will need to be cleared before looking up the [geoDatabase] again. A copy of the original geodatabase * file is created in the cache folder. */ private fun createGeodatabaseCacheDirectory() { try{ // clear cache directory File(cacheDir.path).deleteRecursively() // copy over the original Geodatabase file to be used in the temp cache directory File(getExternalFilesDir(null)?.path + "/ContingentValuesBirdNests.geodatabase").copyTo( File(cacheDir.path + "/ContingentValuesBirdNests.geodatabase") ) }catch (e: Exception){ val message = "Error setting .geodatabase file: " + e.message Log.e(TAG, message) Toast.makeText(this, message, Toast.LENGTH_SHORT).show() } } /** * Create buffer graphics for the features and adds the graphics to * the [graphicsOverlay] */ private fun queryFeatures() { // create buffer graphics for the features val queryParameters = QueryParameters().apply { // set the where clause to filter for buffer sizes greater than 0 whereClause = "BufferSize > 0" } // query the features using the queryParameters on the featureTable val queryFeaturesFuture = featureTable?.queryFeaturesAsync(queryParameters) queryFeaturesFuture?.addDoneListener { try { // clear the existing graphics graphicsOverlay.graphics.clear() // call get on the future to get the result val resultIterator = queryFeaturesFuture.get().iterator() if (resultIterator.hasNext()) { // create an array of graphics to add to the graphics overlay val graphics = mutableListOf<Graphic>() // create graphic for each query result by calling createGraphic(feature) //while (resultIterator.hasNext()) graphics.add(createGraphic(resultIterator.next())) queryFeaturesFuture.get().iterator().forEach { graphics.add(createGraphic(it)) } // add the graphics to the graphics overlay graphicsOverlay.graphics.addAll(graphics) } else { val message = "No features found with BufferSize > 0" Toast.makeText(this, message, Toast.LENGTH_LONG).show() Log.d(TAG, message) } } catch (e: Exception) { val message = "Error querying features: " + e.message Log.e(TAG, message) Toast.makeText(this, message, Toast.LENGTH_SHORT).show() } } } /** * Create a graphic for the given [feature] and returns a Graphic with the features attributes */ private fun createGraphic(feature: Feature): Graphic { // get the feature's buffer size val bufferSize = feature.attributes["BufferSize"] as Int // get a polygon using the feature's buffer size and geometry val polygon = GeometryEngine.buffer(feature.geometry, bufferSize.toDouble()) // create the outline for the buffers val lineSymbol = SimpleLineSymbol(SimpleLineSymbol.Style.SOLID, Color.BLACK, 2F) // create the buffer symbol val bufferSymbol = SimpleFillSymbol( SimpleFillSymbol.Style.FORWARD_DIAGONAL, Color.RED, lineSymbol ) // create an a graphic and add it to the array. return Graphic(polygon, bufferSymbol) } /** * Open BottomSheetDialog view to handle contingent value interaction. * Once the contingent values have been set and the apply button is clicked, * the function will call validateContingency() to add the feature to the map. */ private fun openBottomSheetView(mapPoint: Point) { // creates a new BottomSheetDialog val dialog = BottomSheetDialog(this) dialog.behavior.state = BottomSheetBehavior.STATE_EXPANDED // set up the first content value attribute setUpStatusAttributes() bottomSheetBinding.apply { // reset bottom sheet values, this is needed to showcase contingent values behavior statusInputLayout.editText?.setText("") protectionInputLayout.editText?.setText("") selectedBuffer.text = "" protectionInputLayout.isEnabled = false bufferSeekBar.isEnabled = false bufferSeekBar.value = bufferSeekBar.valueFrom // set apply button to validate and apply contingency feature on map applyTv.setOnClickListener { // check if the contingent features set is valid and set it to the map if valid validateContingency(mapPoint) dialog.dismiss() } // dismiss on cancel clicked cancelTv.setOnClickListener { dialog.dismiss() } } // clear and set bottom sheet content view to layout, to be able to set the content view on each bottom sheet draw if (bottomSheetBinding.root.parent != null) { (bottomSheetBinding.root.parent as ViewGroup).removeAllViews() } // set the content view to the root of the binding layout dialog.setContentView(bottomSheetBinding.root) // display the bottom sheet view dialog.show() } /** * Retrieve the status fields, add the fields to a ContingentValueDomain, and set the values to the spinner * When status attribute selected, createFeature() is called. */ private fun setUpStatusAttributes() { // get the first field by name val statusField = featureTable?.fields?.find { field -> field.name.equals("Status") } // get the field's domains as coded value domain val codedValueDomain = statusField?.domain as CodedValueDomain // get the coded value domain's coded values val statusCodedValues = codedValueDomain.codedValues // get the selected index if applicable val statusNames = mutableListOf<String>() statusCodedValues.forEach { statusNames.add(it.name) } // get the items to be added to the spinner adapter val adapter = ArrayAdapter(bottomSheetBinding.root.context, R.layout.list_item, statusNames) (bottomSheetBinding.statusInputLayout.editText as? AutoCompleteTextView)?.apply { setAdapter(adapter) setOnItemClickListener { _, _, position, _ -> // get the CodedValue of the item selected, and create a feature needed for feature attributes createFeature(statusCodedValues[position]) } } } /** * Set up the [feature] using the status attribute's coded value * by loading the [featureTable]'s Contingent Value Definition. * This function calls setUpProtectionAttributes() once the [feature] has been set */ private fun createFeature(codedValue: CodedValue) { // get the contingent values definition from the feature table val contingentValueDefinition = featureTable?.contingentValuesDefinition if (contingentValueDefinition != null) { // load the contingent values definition contingentValueDefinition.loadAsync() contingentValueDefinition.addDoneLoadingListener { // create a feature from the feature table and set the initial attribute feature = featureTable?.createFeature() as ArcGISFeature feature?.attributes?.set("Status", codedValue.code) setUpProtectionAttributes() } } else { val message = "Error retrieving ContingentValuesDefinition from the FeatureTable" Toast.makeText(this, message, Toast.LENGTH_SHORT).show() Log.e(TAG, message) } } /** * Retrieve the protection attribute fields, add the fields to a ContingentCodedValue, and set the values to the spinner * When status attribute selected, showBufferSeekbar() is called. */ private fun setUpProtectionAttributes() { // set the bottom sheet view to enable the Protection attribute, and disable input elsewhere bottomSheetBinding.apply { protectionInputLayout.isEnabled = true bufferSeekBar.isEnabled = false bufferSeekBar.value = bufferSeekBar.valueFrom protectionInputLayout.editText?.setText("") selectedBuffer.text = "" } // get the contingent value results with the feature for the protection field val contingentValuesResult = featureTable?.getContingentValues(feature, "Protection") if (contingentValuesResult != null) { // get contingent coded values by field group // convert the list of ContingentValues to a list of CodedValue val protectionCodedValues = mutableListOf<CodedValue>() contingentValuesResult.contingentValuesByFieldGroup["ProtectionFieldGroup"]?.forEach { contingentValue -> protectionCodedValues.add((contingentValue as ContingentCodedValue).codedValue) } // set the items to be added to the spinner adapter val adapter = ArrayAdapter( bottomSheetBinding.root.context, R.layout.list_item, protectionCodedValues.map { it.name }) (bottomSheetBinding.protectionInputLayout.editText as? AutoCompleteTextView)?.apply { setAdapter(adapter) setOnItemClickListener { _, _, position, _ -> // set the protection CodedValue of the item selected, and then enable buffer seekbar feature?.attributes?.set("Protection", protectionCodedValues[position].code) showBufferSeekbar() } } } else { val message = "Error loading ContingentValuesResult from the FeatureTable" Log.e(TAG, message) Toast.makeText(this, message, Toast.LENGTH_SHORT).show() } } /** * Retrieve the buffer attribute fields, add the fields to a ContingentRangeValue, * and set the values to a SeekBar */ private fun showBufferSeekbar() { // set the bottom sheet view to enable the buffer attribute bottomSheetBinding.apply { bufferSeekBar.isEnabled = true selectedBuffer.text = "" } // get the contingent value results using the feature and field val contingentValueResult = featureTable?.getContingentValues(feature, "BufferSize") val bufferSizeGroupContingentValues = (contingentValueResult?.contingentValuesByFieldGroup?.get("BufferSizeFieldGroup")?.get(0) as ContingentRangeValue) // set the minimum and maximum possible buffer sizes val minValue = bufferSizeGroupContingentValues.minValue as Int val maxValue = bufferSizeGroupContingentValues.maxValue as Int // check if there can be a max value, if not disable SeekBar & set value to attribute size to 0 if (maxValue > 0) { // get SeekBar instance from the binding layout bottomSheetBinding.bufferSeekBar.apply { // set the min, max and current value of the SeekBar valueFrom = minValue.toFloat() valueTo = maxValue.toFloat() value = valueFrom // set the initial attribute and the text to the min of the ContingentRangeValue feature?.attributes?.set("BufferSize", value.toInt()) bottomSheetBinding.selectedBuffer.text = value.toInt().toString() // set the change listener to update the attribute value and the displayed value to the SeekBar position addOnChangeListener { _, value, _ -> feature?.attributes?.set("BufferSize", value.toInt()) bottomSheetBinding.selectedBuffer.text = value.toInt().toString() } } } else { // max value is 0, so disable seekbar and update the attribute value accordingly bottomSheetBinding.apply { bufferSeekBar.isEnabled = false selectedBuffer.text = "0" } feature?.attributes?.set("BufferSize", 0) } } /** * Ensure that the selected values are a valid combination. * If contingencies are valid, then display [feature] on the [mapPoint] */ private fun validateContingency(mapPoint: Point) { // check if all the features have been set if (featureTable == null) { val message = "Input all values to add a feature to the map" Toast.makeText(this, message, Toast.LENGTH_SHORT).show() Log.e(TAG, message) return } try { // validate the feature's contingencies val contingencyViolations = featureTable?.validateContingencyConstraints(feature) if (contingencyViolations?.isEmpty() == true) { // if there are no contingency violations in the array, // the feature is valid and ready to add to the feature table // create a symbol to represent a bird's nest val symbol = SimpleMarkerSymbol(SimpleMarkerSymbol.Style.CIRCLE, Color.BLACK, 11F) // add the graphic to the graphics overlay graphicsOverlay.graphics.add(Graphic(mapPoint, symbol)) feature?.geometry = mapPoint val graphic = feature?.let { createGraphic(it) } // add the feature to the feature table featureTable?.addFeatureAsync(feature) featureTable?.addDoneLoadingListener { // add the graphic to the graphics overlay graphicsOverlay.graphics.add(graphic) } } else { val message = "Invalid contingent values: " + (contingencyViolations?.size?: 0) + " violations found." Toast.makeText(this, message, Toast.LENGTH_SHORT).show() Log.e(TAG, message) } } catch (e: Exception) { val message = "Invalid contingent values: " + e.message Toast.makeText(this, message, Toast.LENGTH_SHORT).show() Log.e(TAG, message) } } override fun onPause() { mapView.pause() super.onPause() } override fun onResume() { super.onResume() mapView.resume() } override fun onDestroy() { mapView.dispose() // closing the GeoDatabase will commit the transactions made to the temporary ".geodatabase" file // then removes the temporary ".geodatabase-wal" and ".geodatabase-shm" files from the cache dir geoDatabase?.close() super.onDestroy() } }
apache-2.0
589939505cda427c87c2285f3584d408
45.906383
126
0.64819
5.104422
false
false
false
false
daemontus/Distributed-CTL-Model-Checker
src/main/kotlin/com/github/sybila/checker/solver/BitSetSolver.kt
3
1826
package com.github.sybila.checker.solver import com.github.sybila.checker.Solver import com.github.sybila.checker.byTheWay import java.nio.ByteBuffer import java.util.* class BitSetSolver( private val nBits: Int ) : Solver<BitSet> { override fun BitSet.prettyPrint(): String = this.toString() override val tt: BitSet = BitSet().apply { this.set(0, nBits) } override val ff: BitSet = BitSet() override fun BitSet.and(other: BitSet): BitSet = (this.clone() as BitSet).apply { this.and(other) } override fun BitSet.or(other: BitSet): BitSet = (this.clone() as BitSet).apply { this.or(other) } override fun BitSet.not(): BitSet = (tt.clone() as BitSet).apply { this.andNot(this@not) } override fun BitSet.isSat(): Boolean = !this.isEmpty.byTheWay { SolverStats.solverCall() } override fun BitSet.minimize() {} override fun BitSet.byteSize(): Int = 4 + this.toLongArray().size * 8 override fun ByteBuffer.putColors(colors: BitSet): ByteBuffer = this.apply { val array = colors.toLongArray() this.putInt(array.size) array.forEach { this.putLong(it) } } override fun ByteBuffer.getColors(): BitSet { val array = LongArray(this.int) { this.long } return BitSet.valueOf(array) } override fun BitSet.transferTo(solver: Solver<BitSet>): BitSet = this.clone() as BitSet override fun BitSet.canSat(): Boolean = !this.isEmpty override fun BitSet.canNotSat(): Boolean = this.isEmpty override fun BitSet.andNot(other: BitSet): Boolean = (this.clone() as BitSet).run { this.andNot(other) !this.isEmpty }.byTheWay { SolverStats.solverCall() } override fun BitSet.equals(other: BitSet): Boolean = (this == other).byTheWay { SolverStats.solverCall() } }
gpl-3.0
3c427e14b3061ac7703997b62f6dfd39
32.833333
110
0.667579
3.901709
false
false
false
false
rori-dev/lunchbox
backend-spring-kotlin/src/test/kotlin/lunchbox/domain/service/LunchOfferUpdateTest.kt
1
1104
package lunchbox.domain.service import io.mockk.Runs import io.mockk.clearAllMocks import io.mockk.every import io.mockk.just import io.mockk.mockk import io.mockk.verify import lunchbox.domain.models.LunchProvider import lunchbox.repository.LunchOfferRepository import lunchbox.util.date.DateValidator import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test class LunchOfferUpdateTest { private val repo = mockk<LunchOfferRepository>() private val worker = mockk<LunchOfferUpdateWorker>() private val testUnit = LunchOfferUpdate(repo, worker) @BeforeEach fun beforeEach() { clearAllMocks() } @Test fun success() { every { repo.deleteBefore(DateValidator.mondayLastWeek()) } just Runs every { worker.refreshOffersOf(any()) } just Runs testUnit.updateOffers() verify(exactly = 1) { repo.deleteBefore(DateValidator.mondayLastWeek()) } for (provider in activeProviders) verify(exactly = 1) { worker.refreshOffersOf(provider) } } // --- mocks 'n' stuff private val activeProviders = LunchProvider.values().filter { it.active } }
mit
4bf53d76adae5ad217e4abbc3ac27ee5
25.926829
77
0.755435
3.971223
false
true
false
false
azizbekian/Spyur
app/src/main/kotlin/com/incentive/yellowpages/ui/detail/DetailsAdapter.kt
1
8899
package com.incentive.yellowpages.ui.detail import android.support.v7.widget.RecyclerView import android.text.TextUtils import android.util.SparseIntArray import android.view.View import android.view.ViewGroup import android.widget.TextView import com.google.android.gms.maps.model.LatLng import com.incentive.yellowpages.R import com.incentive.yellowpages.data.model.ListingResponse import com.incentive.yellowpages.misc.inflate import com.incentive.yellowpages.utils.LogUtils import io.reactivex.functions.Consumer import kotlinx.android.synthetic.main.row_content_contact_info.view.* import kotlinx.android.synthetic.main.row_content_executive.view.* import kotlinx.android.synthetic.main.row_content_listing_in_spyur_url.view.* import kotlinx.android.synthetic.main.row_content_website.view.* import kotlinx.android.synthetic.main.row_title_executives.view.* import java.util.* class DetailsAdapter constructor( val executives: List<String>, val contactInfos: List<ListingResponse.ContactInfo>, val websites: List<String>, val listingInSpyur: String?, val addressClickConsumer: Consumer<LatLng?>) : RecyclerView.Adapter<RecyclerView.ViewHolder>() { companion object { val TITLE_TO_CONTENT_MAP = SparseIntArray(4).apply { put(R.layout.row_title_executives, R.layout.row_content_executive) put(R.layout.row_title_contact_info, R.layout.row_content_contact_info) put(R.layout.row_title_website, R.layout.row_content_website) put(R.layout.row_title_listing_in_spyur, R.layout.row_content_listing_in_spyur_url) } } private val viewTypeHolder: IntArray private val contactInfoContentOffset: Int = (executives.size + if (executives.isNotEmpty()) 1 else 0) + if (contactInfos.isNotEmpty()) 1 else 0 private val websitesContentOffset: Int = contactInfoContentOffset + contactInfos.size + (if (websites.isNotEmpty()) 1 else 0) + (if (contactInfos.isNotEmpty() && contactInfos.size > 1) contactInfos.size - 1 else 0) /* divider between contactInfos*/ private val size: Int = (executives.size + if (executives.isNotEmpty()) 1 else 0) + (contactInfos.size + if (contactInfos.isNotEmpty()) 1 else 0) + (if (contactInfos.isNotEmpty() && contactInfos.size > 1) contactInfos.size - 1 else 0) + /* divider between contactInfos*/ (websites.size + if (websites.isNotEmpty()) 1 else 0) + if (!listingInSpyur.isNullOrBlank()) 2 else 0 init { viewTypeHolder = IntArray(size) val sourceSizes: LinkedList<Int> = LinkedList() val sourceLayoutIds: LinkedList<Int> = LinkedList() sourceSizes.apply { sourceSizes.add(executives.size) sourceSizes.add(contactInfos.size) sourceSizes.add(websites.size) sourceSizes.add(1) } sourceLayoutIds.apply { sourceLayoutIds.add(R.layout.row_title_executives) sourceLayoutIds.add(R.layout.row_title_contact_info) sourceLayoutIds.add(R.layout.row_title_website) sourceLayoutIds.add(R.layout.row_title_listing_in_spyur) } var index = 0 while (index < size) { if (sourceSizes.isEmpty()) break val count = sourceSizes.first if (count == 0) { // do not show this item sourceSizes.removeFirst() sourceLayoutIds.removeFirst() continue } viewTypeHolder[index++] = sourceLayoutIds.first val contentLayoutId = TITLE_TO_CONTENT_MAP[sourceLayoutIds.first] if (contentLayoutId == R.layout.row_content_contact_info) { var j = index for (i in 0 until count) { viewTypeHolder[j] = contentLayoutId j += 2 } j = index + 1 for (i in 0 until count - 1) { viewTypeHolder[j] = R.layout.divider j += 2 } index += count + (count - 1) } else { viewTypeHolder.fill(contentLayoutId, index, index + count) index += count } sourceSizes.removeFirst() sourceLayoutIds.removeFirst() } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder? { val inflatedView = parent.inflate(viewType, parent) return when (viewType) { R.layout.row_title_executives -> ExecutivesTitle(inflatedView) R.layout.row_content_executive -> ExecutivesContent(inflatedView) R.layout.row_title_contact_info -> ContactInfoTitle(inflatedView) R.layout.row_content_contact_info -> ContactInfoContent(inflatedView) R.layout.divider -> Divider(inflatedView) R.layout.row_title_website -> WebsiteTitle(inflatedView) R.layout.row_content_website -> WebsiteContent(inflatedView) R.layout.row_title_listing_in_spyur -> ListingInSpyurTitle(inflatedView) R.layout.row_content_listing_in_spyur_url -> ListingInSpyurContent(inflatedView) else -> null } } override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { LogUtils.i(position) when (holder) { is ExecutivesTitle -> holder.bind(executives.size) is ExecutivesContent -> holder.bind(executives[holder.adapterPosition - 1]) is ContactInfoContent -> holder.bind(contactInfos[(holder.adapterPosition - contactInfoContentOffset) / 2]) is WebsiteContent -> holder.bind(websites[holder.adapterPosition - websitesContentOffset]) is ListingInSpyurContent -> holder.bind(listingInSpyur) } } override fun onViewRecycled(holder: RecyclerView.ViewHolder?) { if (holder is ContactInfoContent) { holder.itemView.phoneNumberContainer.removeAllViews() } super.onViewRecycled(holder) } override fun getItemViewType(position: Int): Int = viewTypeHolder[position] override fun getItemCount(): Int = size inner class ExecutivesTitle(itemView: View) : RecyclerView.ViewHolder(itemView) { fun bind(executivesCount: Int) { itemView.executives_title.text = itemView.resources.getQuantityString(R.plurals.executive, executivesCount) } } inner class ExecutivesContent(itemView: View) : RecyclerView.ViewHolder(itemView) { fun bind(executive: String) { itemView.executive_content.text = executive } } inner class ContactInfoTitle(itemView: View) : RecyclerView.ViewHolder(itemView) inner class ContactInfoContent(itemView: View) : RecyclerView.ViewHolder(itemView) { fun bind(contactInfo: ListingResponse.ContactInfo) { itemView.contactInfoAddress.text = contactInfo.address if (contactInfo.loc != null) { itemView.contactInfoAddress.setOnClickListener { v -> addressClickConsumer.accept(contactInfo.loc) } } if (TextUtils.isEmpty(contactInfo.region)) { itemView.contactInfoRegion.visibility = View.GONE } else { itemView.contactInfoRegion.visibility = View.VISIBLE itemView.contactInfoRegion.text = contactInfo.region } if (contactInfo.phoneNumbers.isEmpty()) { itemView.phoneNumberContainer.visibility = View.GONE } else { itemView.phoneNumberContainer.visibility = View.VISIBLE for (phoneNumber in contactInfo.phoneNumbers) { val phoneNumberRow = itemView.inflate(R.layout.row_content_phone_number, itemView.phoneNumberContainer) val phoneNumberTextView = phoneNumberRow .findViewById(R.id.contactInfoPhoneNumber) as TextView phoneNumberTextView.text = phoneNumber itemView.phoneNumberContainer.addView(phoneNumberRow) } } } } inner class Divider(itemView: View) : RecyclerView.ViewHolder(itemView) inner class WebsiteTitle(itemView: View) : RecyclerView.ViewHolder(itemView) inner class WebsiteContent(itemView: View) : RecyclerView.ViewHolder(itemView) { fun bind(website: String) { itemView.website.text = website } } inner class ListingInSpyurTitle(itemView: View) : RecyclerView.ViewHolder(itemView) inner class ListingInSpyurContent(itemView: View) : RecyclerView.ViewHolder(itemView) { fun bind(listing: String?) { itemView.listingInSpyur.text = listing } } }
gpl-2.0
821ef6b1c8aa777c6657d8aa8a98b739
41.990338
134
0.645691
4.51039
false
false
false
false
proxer/ProxerAndroid
src/main/kotlin/me/proxer/app/chat/pub/room/info/ChatRoomInfoActivity.kt
1
1324
package me.proxer.app.chat.pub.room.info import android.app.Activity import android.os.Bundle import androidx.fragment.app.commitNow import me.proxer.app.R import me.proxer.app.base.DrawerActivity import me.proxer.app.util.extension.getSafeStringExtra import me.proxer.app.util.extension.startActivity /** * @author Ruben Gees */ class ChatRoomInfoActivity : DrawerActivity() { companion object { private const val CHAT_ROOM_ID_EXTRA = "chat_room_id" private const val CHAT_ROOM_NAME_EXTRA = "chat_room_name" fun navigateTo(context: Activity, chatRoomId: String, chatRoomName: String) { context.startActivity<ChatRoomInfoActivity>( CHAT_ROOM_ID_EXTRA to chatRoomId, CHAT_ROOM_NAME_EXTRA to chatRoomName ) } } val chatRoomId: String get() = intent.getSafeStringExtra(CHAT_ROOM_ID_EXTRA) val chatRoomName: String get() = intent.getSafeStringExtra(CHAT_ROOM_NAME_EXTRA) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) title = chatRoomName if (savedInstanceState == null) { supportFragmentManager.commitNow { replace(R.id.container, ChatRoomInfoFragment.newInstance()) } } } }
gpl-3.0
1a5ff8e9e543d5b20cf782c7782b250d
28.422222
85
0.672961
4.312704
false
false
false
false
VladRassokhin/intellij-hcl
src/kotlin/org/intellij/plugins/hcl/terraform/config/model/Variable.kt
1
1192
/* * 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 org.intellij.plugins.hcl.terraform.config.model class Variable(val name: String, vararg properties: PropertyOrBlock = emptyArray()) : Block(TypeModel.Variable, *properties) { fun getDefault(): Any? { return properties.firstOrNull { TypeModel.Variable_Default == it.property?.type }?.property?.value } fun getType(): Any? { return properties.firstOrNull { TypeModel.Variable_Type == it.property?.type }?.property?.value } fun getDescription(): Any? { return properties.firstOrNull { TypeModel.Variable_Description == it.property?.type }?.property?.value } }
apache-2.0
d34583352f44288df8badd6560d9c51b
38.766667
126
0.734899
4.167832
false
false
false
false
christophpickl/gadsu
src/main/kotlin/at/cpickl/gadsu/view/components/inputs/MyComboBox.kt
1
2502
package at.cpickl.gadsu.view.components.inputs import at.cpickl.gadsu.global.Labeled import at.cpickl.gadsu.view.Colors import at.cpickl.gadsu.view.swing.opaque import at.cpickl.gadsu.view.swing.transparent import org.slf4j.LoggerFactory import java.awt.Color import java.awt.Component import java.util.Vector import javax.swing.JComboBox import javax.swing.JLabel import javax.swing.JList import javax.swing.ListCellRenderer import javax.swing.UIManager open class MyComboBox<T : Labeled>(data: List<T>, initValue: T) : JComboBox<T>(Vector(data)) { private val log = LoggerFactory.getLogger(javaClass) init { assert(data.contains(initValue)) selectedItem = initValue setRenderer(LabeledCellRenderer(getRenderer())) // prototypeDisplayValue = initValue // fail: trying to get proper width } @Suppress("UNCHECKED_CAST") var selectedItemTyped: T get() = selectedItem as T set(value) { selectedItem = value if (!selectedItem.equals(value)) { log.warn("Seems as you requested to select an item ({}) which was not contained in this combo box model: {}", value, model) } } // fun setLabeledCellRenderer(): MyComboBox<T> { // setRenderer(LabeledCellRenderer(getRenderer())) // return this // } } /** * Anything that inherits Labeled, can be rendered with this. */ class LabeledCellRenderer<L : Labeled>(private val original: ListCellRenderer<in L>) : ListCellRenderer<L> { override fun getListCellRendererComponent( list: JList<out L>, value: L, index: Int, isSelected: Boolean, cellHasFocus: Boolean): Component? { val rendering = original.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus) val label = rendering as JLabel label.text = value.label // println("value=$value, index=$index, isSelected=$isSelected, focus=$cellHasFocus") // alternate row background if (index == -1) { label.transparent() } else if (isSelected) { label.opaque() label.background = UIManager.getColor("List.selectionBackground") } else { label.opaque() if (index % 2 == 1) { label.background = Colors.BG_ALTERNATE } else { label.background = Color.WHITE } } return rendering } }
apache-2.0
e1395050247fa6de2d9e0652a54c5686
31.921053
125
0.63789
4.5
false
false
false
false
indy256/codelibrary
kotlin/Treap.kt
1
2965
import java.util.Random import java.util.TreeSet // https://en.wikipedia.org/wiki/Treap object Treap { val random = Random() data class Treap( val key: Int, var left: Treap? = null, var right: Treap? = null, var size: Int = 1, val prio: Long = random.nextLong() ) { fun update() { size = 1 + getSize(left) + getSize(right) } } fun getSize(root: Treap?) = root?.size ?: 0 fun split(root: Treap?, minRight: Int): Pair<Treap?, Treap?> { if (root == null) return Pair(null, null) if (root.key >= minRight) { val leftSplit = split(root.left, minRight) root.left = leftSplit.second root.update() return Pair(leftSplit.first, root) } else { val rightSplit = split(root.right, minRight) root.right = rightSplit.first root.update() return Pair(root, rightSplit.second) } } fun merge(left: Treap?, right: Treap?): Treap? { if (left == null) return right if (right == null) return left if (left.prio > right.prio) { left.right = merge(left.right, right) left.update() return left } else { right.left = merge(left, right.left) right.update() return right } } fun insert(root: Treap?, key: Int): Treap? { val t = split(root, key) return merge(merge(t.first, Treap(key)), t.second) } fun remove(root: Treap?, key: Int): Treap? { val t = split(root, key) return merge(t.first, split(t.second, key + 1).second) } fun kth(root: Treap, k: Int): Int { if (k < getSize(root.left)) return kth(root.left!!, k) else if (k > getSize(root.left)) return kth(root.right!!, k - getSize(root.left) - 1) return root.key } fun print(root: Treap?) { if (root == null) return print(root.left) println(root.key) print(root.right) } // random test @JvmStatic fun main(args: Array<String>) { val time = System.currentTimeMillis() var treap: Treap? = null val set = TreeSet<Int>() for (i in 0..999999) { val key = random.nextInt(100000) if (random.nextBoolean()) { treap = remove(treap, key) set.remove(key) } else if (!set.contains(key)) { treap = insert(treap, key) set.add(key) } if (set.size != getSize(treap)) throw RuntimeException() } for (i in 0 until getSize(treap)) { if (!set.contains(kth(treap!!, i))) throw RuntimeException() } println(System.currentTimeMillis() - time) } }
unlicense
357125e73a32a9c81ba34481894befb6
27.509615
66
0.499494
3.840674
false
false
false
false
lanhuaguizha/Christian
app/src/main/java/com/christian/nav/disciple/DiscipleDetailFragment.kt
1
13711
/** * Copyright Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.christian.nav.disciple import android.content.Context import android.net.Uri import android.os.Bundle import android.util.Log import android.view.* import android.widget.ProgressBar import androidx.fragment.app.Fragment import androidx.recyclerview.widget.LinearLayoutManager import com.christian.R import com.christian.common.data.Chat import com.christian.common.getDateAndCurrentTime import com.christian.databinding.FragmentDetailDiscipleBinding import com.christian.view.ItemDecoration import com.christian.view.showPopupMenu import com.firebase.ui.database.FirebaseRecyclerOptions import com.google.android.material.snackbar.Snackbar import com.google.firebase.auth.FirebaseAuth import com.google.firebase.auth.ktx.auth import com.google.firebase.database.DatabaseReference import com.google.firebase.database.FirebaseDatabase import com.google.firebase.database.core.utilities.PushIdGenerator import com.google.firebase.database.ktx.database import com.google.firebase.database.snapshot.ChildKey import com.google.firebase.ktx.Firebase import com.google.firebase.storage.StorageReference import com.google.firebase.storage.ktx.storage import com.lxj.xpopup.interfaces.OnSelectListener import com.lxj.xpopup.util.XPopupUtils import kotlinx.android.synthetic.main.activity_detail_disciple.* class DiscipleDetailFragment : Fragment() { private lateinit var discipleDetailActivity: DiscipleDetailActivity lateinit var binding: FragmentDetailDiscipleBinding private lateinit var manager: LinearLayoutManager // Firebase instance variables private lateinit var auth: FirebaseAuth lateinit var db: FirebaseDatabase private lateinit var adapter: FriendlyMessageAdapter private val openDocument = registerForActivityResult(MyOpenDocumentContract()) { uri -> if (uri != null) onImageSelected(uri) } override fun onAttach(context: Context) { super.onAttach(context) discipleDetailActivity = requireActivity() as DiscipleDetailActivity } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { setHasOptionsMenu(true) // This codelab uses View Binding // See: https://developer.android.com/topic/libraries/view-binding binding = FragmentDetailDiscipleBinding.inflate(layoutInflater) // When running in debug mode, connect to the Firebase Emulator Suite // "10.0.2.2" is a special value which allows the Android emulator to // connect to "localhost" on the host computer. The port values are // defined in the firebase.json file. // Initialize Firebase Auth and check if the user is signed in auth = Firebase.auth // Initialize Realtime Database db = Firebase.database val messagesRef = db.reference.child(MESSAGES_CHILD) // The FirebaseRecyclerAdapter class and options come from the FirebaseUI library // See: https://github.com/firebase/FirebaseUI-Android val options = FirebaseRecyclerOptions.Builder<Chat>() .setQuery(messagesRef, Chat::class.java) .build() adapter = FriendlyMessageAdapter(options, getUserName(), discipleDetailActivity) binding.progressBar.visibility = ProgressBar.INVISIBLE manager = LinearLayoutManager(requireActivity()) manager.stackFromEnd = true binding.messageRecyclerView.layoutManager = manager binding.messageRecyclerView.adapter = adapter binding.messageRecyclerView.addItemDecoration(ItemDecoration()) binding.progressBar.isIndeterminate = true binding.messageRecyclerView.setProgressBar(binding.progressBar) // Scroll down when a new message arrives // See MyScrollToBottomObserver for details adapter.registerAdapterDataObserver( MyScrollToBottomObserver(binding.messageRecyclerView, adapter, manager) ) // Disable the send button when there's no text in the input field // See MyButtonObserver for details binding.messageEditText.addTextChangedListener(MyButtonObserver(binding.sendButton)) binding.messageEditText.setOnClickListener { binding.messageRecyclerView.smoothScrollToPosition(adapter.itemCount -1) } binding.messageEditText.setOnFocusChangeListener { _, hasFocus -> if (hasFocus) { binding.messageRecyclerView.smoothScrollToPosition(adapter.itemCount -1) } } // When the send button is clicked, send a text message binding.sendButton.setOnClickListener { sendMessage() } // When the image button is clicked, launch the image picker binding.addMessageImageView.setOnClickListener { openDocument.launch(arrayOf("image/*")) } adapter.startListening() return binding.root } private fun sendMessage() { val key = db.reference.child(MESSAGES_CHILD).push().key.toString() val friendlyMessage = Chat( discipleDetailActivity.subTitle, binding.messageEditText.text.toString(), getUserName(), getPhotoUrl(), null, chatId = key, createTime = getDateAndCurrentTime(), ) db.reference.child(MESSAGES_CHILD).child(key).setValue(friendlyMessage) .addOnSuccessListener { } .addOnFailureListener { if (isAdded) { toAuthActivity() } } binding.messageEditText.setText("") } private fun toAuthActivity() { val discipleDetailActivity = requireActivity() as DiscipleDetailActivity Snackbar.make(discipleDetailActivity.cl_nav, R.string.please_sign_in, Snackbar.LENGTH_SHORT) .show() discipleDetailActivity.signIn() } override fun onDestroyView() { super.onDestroyView() adapter.stopListening() } private fun onImageSelected(uri: Uri) { val key = db.reference.child(MESSAGES_CHILD).push().key.toString() Log.d(TAG, "Uri: $uri") val user = auth.currentUser val tempMessage = Chat(discipleDetailActivity.subTitle, null, getUserName(), getPhotoUrl(), LOADING_IMAGE_URL, chatId = key, createTime = getDateAndCurrentTime(), ) db.reference .child(MESSAGES_CHILD) .child(key) .setValue( tempMessage, DatabaseReference.CompletionListener { databaseError, databaseReference -> if (databaseError != null) { Log.w( TAG, "Unable to write message to database.", databaseError.toException() ) toAuthActivity() return@CompletionListener } // Build a StorageReference and then upload the file val key = databaseReference.key val storageReference = Firebase.storage .getReference(user!!.uid) .child(key!!) .child(uri.lastPathSegment!!) putImageInStorage(storageReference, uri, key) }) } private fun putImageInStorage(storageReference: StorageReference, uri: Uri, key: String) { // First upload the image to Cloud Storage storageReference.putFile(uri) .addOnSuccessListener( requireActivity() ) { taskSnapshot -> // After the image loads, get a public downloadUrl for the image // and add it to the message. taskSnapshot.metadata!!.reference!!.downloadUrl .addOnSuccessListener { uri -> val friendlyMessage = Chat(discipleDetailActivity.subTitle, null, getUserName(), getPhotoUrl(), uri.toString(), chatId = key, createTime = getDateAndCurrentTime(),) db.reference .child(MESSAGES_CHILD) .child(key!!) .setValue(friendlyMessage) } } .addOnFailureListener(requireActivity()) { e -> Log.w( TAG, "Image upload task was unsuccessful.", e ) } } private fun getPhotoUrl(): String? { val user = auth.currentUser return user?.photoUrl?.toString() } private fun getUserName(): String? { val user = auth.currentUser return if (user != null) { user.displayName } else ANONYMOUS } companion object { private const val TAG = "MainActivity" const val MESSAGES_CHILD = "chats" const val ANONYMOUS = "anonymous" private const val LOADING_IMAGE_URL = "" } override fun onOptionsItemSelected(item: MenuItem): Boolean { return when (item.itemId) { // R.id.menu_share -> { // Snackbar.make(getString(R.string.toast_share)).show() // true // } // R.id.menu_favorite -> { // snackbar(getString(R.string.toast_favorite)).show() // true // } // R.id.menu_translate -> { // snackbar(getString(R.string.toast_translate)).show() // true // } // R.id.menu_read -> { // snackbar(getString(R.string.toast_read)).show() // true // } R.id.menu_options_nav_detail -> { val onSelectListener = OnSelectListener { _, text -> when(text) { getString(R.string.action_mute) -> { // actionShareText(requireActivity(), gospel) } getString(R.string.action_unfollow) -> { // actionFavorite(gospel, navId, requireActivity()) } getString(R.string.action_delete) -> { // toEditorActivity(requireActivity(), navId, gospelId) } getString(R.string.action_block) -> { // DeleteDialogFragment(requireActivity(), navId, gospelId).show( // supportFragmentManager, // "ExitDialogFragment" // ) } } } // if (com.christian.common.auth.currentUser?.uid == userId) { val array = if (true) { // val array = if (gospel.like.contains(com.christian.common.auth.currentUser?.uid)) { arrayOf( getString(R.string.action_mute), getString(R.string.action_unfollow), getString(R.string.action_delete), getString(R.string.action_block) ) } else { arrayOf( getString(R.string.action_mute), getString(R.string.action_follow), getString(R.string.action_delete), getString(R.string.action_block) ) } showPopupMenu( requireActivity().findViewById(R.id.menu_options_nav_detail), requireActivity(), array, XPopupUtils.dp2px(requireActivity(), -48f), onSelectListener = onSelectListener ) // } else { // val array = if (gospel.like.contains(com.christian.common.auth.currentUser?.uid)) { // arrayOf( // getString(R.string.action_share), // getString(R.string.action_favorite_delete), // ) // } else { // arrayOf( // getString(R.string.action_share), // getString(R.string.action_favorite), // ) // } // showPopupMenu( // findViewById(R.id.menu_options_nav_detail), this@GospelDetailActivity, // array, // XPopupUtils.dp2px(this, -48f), // onSelectListener = onSelectListener // ) // } true } else -> super.onOptionsItemSelected(item) } } }
gpl-3.0
85a7e569f902d804ff6b1bbcefc604a4
39.445428
132
0.575086
5.287698
false
false
false
false
Shynixn/PetBlocks
petblocks-sponge-plugin/src/main/java/com/github/shynixn/petblocks/sponge/logic/business/listener/DamagePetListener.kt
1
5428
@file:Suppress("CAST_NEVER_SUCCEEDS", "unused") package com.github.shynixn.petblocks.sponge.logic.business.listener import com.flowpowered.math.vector.Vector3d import com.github.shynixn.petblocks.api.business.service.CombatPetService import com.github.shynixn.petblocks.api.business.service.HealthService import com.github.shynixn.petblocks.api.business.service.PersistencePetMetaService import com.github.shynixn.petblocks.api.business.service.PetService import com.github.shynixn.petblocks.api.persistence.entity.AIFleeInCombat import com.github.shynixn.petblocks.api.persistence.entity.AIHealth import com.github.shynixn.petblocks.api.sponge.event.PetPreSpawnEvent import com.github.shynixn.petblocks.sponge.logic.business.extension.toPosition import com.github.shynixn.petblocks.sponge.logic.business.extension.toVector import com.google.inject.Inject import org.spongepowered.api.entity.Entity import org.spongepowered.api.entity.living.player.Player import org.spongepowered.api.event.Listener import org.spongepowered.api.event.cause.entity.damage.DamageTypes import org.spongepowered.api.event.cause.entity.damage.source.DamageSources import org.spongepowered.api.event.entity.DamageEntityEvent import java.util.* /** * Created by Shynixn 2018. * <p> * Version 1.2 * <p> * MIT License * <p> * Copyright (c) 2018 by Shynixn * <p> * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * <p> * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * <p> * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ class DamagePetListener @Inject constructor( private val petService: PetService, private val combatPetService: CombatPetService, private val healthService: HealthService, private val persistencePetMetaService: PersistencePetMetaService ) { /** * The [event] gets called when a entity gets damaged. Redirects the damage to the PetBlocks implementation. */ @Listener fun onEntityReceiveDamageEvent(event: DamageEntityEvent) { if (petService.findPetByEntity(event.targetEntity) != null) { val pet = petService.findPetByEntity(event.targetEntity)!! event.isCancelled = true healthService.damagePet(pet.meta, event.finalDamage) if (event.cause.containsType(DamageSources.FALLING::class.java)) { combatPetService.flee(pet.meta) } return } if (event.source != DamageTypes.FALL && event.targetEntity is Player) { if (!persistencePetMetaService.hasPetMeta(event.targetEntity)) { return } val petMeta = persistencePetMetaService.getPetMetaFromPlayer(event.targetEntity) combatPetService.flee(petMeta) } } /** * The [event] gets called when a pet damages another entity. Cancels the damage per default. */ @Listener fun onEntityDamageByEntityEvent(event: DamageEntityEvent) { if (!event.cause.first(Entity::class.java).isPresent) { return } val damager = event.cause.first(Entity::class.java).get() if (petService.findPetByEntity(damager) != null) { event.isCancelled = true return } if (petService.findPetByEntity(event.targetEntity) != null) { val pet = petService.findPetByEntity(event.targetEntity)!! combatPetService.flee(pet.meta) val vector = event.targetEntity.transform.toPosition().subtract(damager.transform.toPosition()).toVector().normalize().mul(0.5) pet.setVelocity(Vector3d(vector.x, 0.1, vector.z)) } } /** * The [event] gets called when a pet tries to get spawned by a player. Checks if the pet is currently respawning blocked. */ @Listener fun onPetSpawnEvent(event: PetPreSpawnEvent) { if (event.petMeta.aiGoals.firstOrNull { a -> a is AIHealth } != null) { val aiHealth = event.petMeta.aiGoals.firstOrNull { a -> a is AIHealth } as AIHealth if (aiHealth.currentRespawningDelay > 0) { event.isCancelled = true } return } if (event.petMeta.aiGoals.firstOrNull { a -> a is AIFleeInCombat } != null) { val aiFleeInCombat = event.petMeta.aiGoals.firstOrNull { a -> a is AIFleeInCombat } as AIFleeInCombat if (aiFleeInCombat.currentAppearsInSeconds > 0) { event.isCancelled = true } return } } }
apache-2.0
d08f923448341a9ecda9f65d32a37825
38.34058
139
0.703758
4.21756
false
false
false
false
idanarye/nisui
cli/src/main/kotlin/nisui/cli/ExperimentSubcommand.kt
1
3707
package nisui.cli import org.slf4j.LoggerFactory import java.io.InputStream import java.io.PrintStream import picocli.CommandLine import nisui.core.ExperimentFunction import nisui.core.ExperimentValuesHandler import nisui.core.NisuiFactory import nisui.core.ExperimentFunctionCreationException @CommandLine.Command( name = "experiment", description = ["Commands for dealing with the experminent runner, regardless of saved data-points or results."] ) public class ExperimentSubcommand(nisuiFactory: NisuiFactory) : CommandGroup(nisuiFactory) { companion object { private val logger = LoggerFactory.getLogger(this.javaClass.declaringClass) } override fun getNames(): Array<String> { return arrayOf("experiment", "e") } @CommandLine.Command( name = "info", description = ["Print static information (data-point and result layout) on the experiment."] ) inner class Info : SubCommand() { override fun getNames(): Array<String> { return arrayOf("info") } override fun run(in_: InputStream?, out_: PrintStream) { val experimentFunction = nisuiFactory.createExperimentFunction() printHandler("Data Points", experimentFunction.getDataPointHandler(), out_) printHandler("Experiment Results", experimentFunction.getExperimentResultHandler(), out_) } private fun printHandler(caption: String, handler: ExperimentValuesHandler<Any>, out_: PrintStream) { out_.printf("%s:\n", caption) for (field in handler.fields()) { out_.printf(" %s: %s", field.name, field.type.simpleName) val enumConstants = field.getType().getEnumConstants() if (enumConstants != null) { out_.print('(') enumConstants.forEachIndexed { i, enumConstant -> if (0 < i) { out_.print('|') } out_.print(enumConstant) } out_.print(')') } out_.println() } } } @CommandLine.Command( name = "run", description = ["Run the experiment once."] ) inner class Run : SubCommand() { override fun getNames(): Array<String> { return arrayOf("run") } @CommandLine.Option(names = ["-s", "--seed"], description = ["Run the experiment with a specific seed. Leave out for random seed."]) var seed: Long = 0 @CommandLine.Parameters(arity = "0..*", paramLabel = "<name>=<value>", description = ["Data-point fields."]) var dataPointValues: ArrayList<String> = arrayListOf() override fun run(in_: InputStream?, out_: PrintStream) { run(out_, nisuiFactory.createExperimentFunction()) } private fun <D, R> run(out_: PrintStream, experimentFunction: ExperimentFunction<D, R>) { val dataPointHandler = experimentFunction.getDataPointHandler() val dataPoint = parseValueAssignment(dataPointHandler, dataPointValues) val seed = if (this.seed == 0.toLong()) { val seed = System.currentTimeMillis() logger.info("Picking seed = {}", seed) seed } else { this.seed } val experimentResult = experimentFunction.runExperiment(dataPoint, seed) for (field in experimentFunction.getExperimentResultHandler().fields()) { out_.printf("%s: %s\n", field.getName(), field.get(experimentResult)) } } } }
mit
c597948a00162b97f8af77dd6895a300
36.07
140
0.594011
4.922975
false
false
false
false
robinverduijn/gradle
subprojects/kotlin-dsl/src/main/kotlin/org/gradle/kotlin/dsl/cache/ScriptCache.kt
1
3991
/* * Copyright 2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.kotlin.dsl.cache import org.gradle.api.Project import org.gradle.cache.CacheRepository import org.gradle.cache.internal.CacheKeyBuilder import org.gradle.cache.internal.CacheKeyBuilder.CacheKeySpec import org.gradle.caching.internal.controller.BuildCacheController import org.gradle.internal.id.UniqueId import org.gradle.internal.scopeids.id.BuildInvocationScopeId import org.gradle.internal.time.Time.startTimer import org.gradle.kotlin.dsl.support.serviceOf import java.io.File internal class ScriptCache( private val cacheRepository: CacheRepository, private val cacheKeyBuilder: CacheKeyBuilder, private val hasBuildCacheIntegration: Boolean ) { fun cacheDirFor( cacheKeySpec: CacheKeySpec, scriptTarget: Any? = null, displayName: String = "", initializer: (File) -> Unit ): File { val cacheKey = cacheKeyFor(cacheKeySpec) return cacheRepository.cache(cacheKey) .withProperties(cacheProperties) .withInitializer { initializeCacheDir( cacheDirOf(it.baseDir).apply { mkdir() }, cacheKey, scriptTarget, displayName, initializer ) }.open().run { close() cacheDirOf(baseDir) } } private val cacheProperties = mapOf("version" to "15") private fun cacheDirOf(baseDir: File) = File(baseDir, "cache") private fun cacheKeyFor(spec: CacheKeySpec): String = cacheKeyBuilder.build(spec) private fun initializeCacheDir( cacheDir: File, cacheKey: String, scriptTarget: Any?, displayName: String, initializer: (File) -> Unit ) { val cacheController = if (hasBuildCacheIntegration) buildCacheControllerOf(scriptTarget) else null if (cacheController != null) { val buildCacheKey = ScriptBuildCacheKey(displayName, cacheKey) val buildInvocationId = buildInvocationIdOf(scriptTarget).asString() val existing = cacheController.load(LoadDirectory(cacheDir, buildCacheKey, buildInvocationId)) if (!existing.isPresent) { val executionTime = executionTimeMillisOf { initializer(cacheDir) } cacheController.store( StoreDirectory( cacheDir, buildCacheKey, PackMetadata(buildInvocationId, executionTime) ) ) } } else { initializer(cacheDir) } } private fun buildCacheControllerOf(scriptTarget: Any?): BuildCacheController? = (scriptTarget as? Project) ?.serviceOf<BuildCacheController>() ?.takeIf { it.isEnabled } private fun buildInvocationIdOf(scriptTarget: Any?): UniqueId = (scriptTarget as Project) .gradle.serviceOf<BuildInvocationScopeId>() .id } private inline fun executionTimeMillisOf(action: () -> Unit) = startTimer().run { action() elapsedMillis } internal operator fun CacheKeySpec.plus(files: List<File>) = files.fold(this, CacheKeySpec::plus)
apache-2.0
a852f4bfb5ca827e97f1d86a5d6ceb4f
27.304965
106
0.63092
4.843447
false
false
false
false
konachan700/Mew
software/MeWSync/app/src/main/java/com/mewhpm/mewsync/data/BleDevice.kt
1
681
package com.mewhpm.mewsync.data import com.j256.ormlite.field.DatabaseField import com.j256.ormlite.table.DatabaseTable @DatabaseTable(tableName = "BleDevice") class BleDevice { constructor() constructor(id: Long, mac: String, name: String) { this.id = id this.mac = mac this.name = name } companion object { const val EMPTY = "" } @DatabaseField(columnName = "id", generatedId = true) var id: Long = 0 @DatabaseField(index = true) var mac: String = EMPTY @DatabaseField var name: String = EMPTY @DatabaseField var text: String = EMPTY @DatabaseField var default: Boolean = false }
gpl-3.0
91c714aa4bf0b819784096f4edd75103
19.666667
57
0.64464
3.913793
false
false
false
false
square/leakcanary
leakcanary-android-core/src/main/java/leakcanary/internal/navigation/BackstackFrame.kt
2
1433
package leakcanary.internal.navigation import android.os.Parcel import android.os.Parcelable import android.util.SparseArray import android.view.View internal class BackstackFrame : Parcelable { val screen: Screen private val viewState: SparseArray<Parcelable>? private constructor( source: Parcel ) { this.screen = source.readSerializable() as Screen @Suppress("UNCHECKED_CAST") this.viewState = source.readSparseArray(javaClass.classLoader) } constructor( screen: Screen ) { this.screen = screen viewState = null } constructor( screen: Screen, view: View ) { this.screen = screen viewState = SparseArray() view.saveHierarchyState(viewState) } fun restore(view: View) { if (viewState != null) { view.restoreHierarchyState(viewState) } } override fun describeContents() = 0 @Suppress("UNCHECKED_CAST") override fun writeToParcel( dest: Parcel, flags: Int ) { dest.writeSerializable(screen) dest.writeSparseArray(viewState as SparseArray<Any>?) } companion object { @Suppress("UNCHECKED_CAST") @JvmField val CREATOR = object : Parcelable.Creator<BackstackFrame> { override fun createFromParcel(source: Parcel): BackstackFrame { return BackstackFrame(source) } override fun newArray(size: Int): Array<BackstackFrame?> { return arrayOfNulls(size) } } } }
apache-2.0
f4ec2d0132eaaafc8de32a213ce0c5ce
20.712121
73
0.686671
4.464174
false
false
false
false
owncloud/android
owncloudApp/src/main/java/com/owncloud/android/presentation/ui/settings/SettingsActivity.kt
2
4514
/** * ownCloud Android client application * * @author Juan Carlos Garrote Gascón * @author David Crespo Ríos * * Copyright (C) 2021 ownCloud GmbH. * <p> * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2, * as published by the Free Software Foundation. * <p> * 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. * <p> * 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.owncloud.android.presentation.ui.settings import android.content.Intent import android.os.Bundle import android.view.MenuItem import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.widget.Toolbar import androidx.constraintlayout.widget.ConstraintLayout import androidx.core.view.isVisible import com.owncloud.android.R import com.owncloud.android.presentation.ui.settings.fragments.SettingsAdvancedFragment import com.owncloud.android.presentation.ui.settings.fragments.SettingsFragment import com.owncloud.android.presentation.ui.settings.fragments.SettingsLogsFragment import com.owncloud.android.presentation.ui.settings.fragments.SettingsMoreFragment import com.owncloud.android.presentation.ui.settings.fragments.SettingsPictureUploadsFragment import com.owncloud.android.presentation.ui.settings.fragments.SettingsSecurityFragment import com.owncloud.android.presentation.ui.settings.fragments.SettingsVideoUploadsFragment import com.owncloud.android.ui.activity.FileDisplayActivity class SettingsActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_settings) val toolbar = findViewById<Toolbar>(R.id.standard_toolbar).apply { isVisible = true } findViewById<ConstraintLayout>(R.id.root_toolbar).apply { isVisible = false } setSupportActionBar(toolbar) updateToolbarTitle() supportActionBar?.setDisplayHomeAsUpEnabled(true) supportFragmentManager.addOnBackStackChangedListener { updateToolbarTitle() } if (savedInstanceState != null) return redirectToSubsection(intent) } private fun updateToolbarTitle() { val titleId = when (supportFragmentManager.fragments.lastOrNull()) { is SettingsSecurityFragment -> R.string.prefs_subsection_security is SettingsLogsFragment -> R.string.prefs_subsection_logging is SettingsPictureUploadsFragment -> R.string.prefs_subsection_picture_uploads is SettingsVideoUploadsFragment -> R.string.prefs_subsection_video_uploads is SettingsAdvancedFragment -> R.string.prefs_subsection_advanced is SettingsMoreFragment -> R.string.prefs_subsection_more else -> R.string.actionbar_settings } supportActionBar?.setTitle(titleId) } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { android.R.id.home -> { if (supportFragmentManager.backStackEntryCount > 0) { supportFragmentManager.popBackStack() } else { intent = Intent(this, FileDisplayActivity::class.java).apply { addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP) } startActivity(intent) } } } return super.onOptionsItemSelected(item) } private fun redirectToSubsection(intent: Intent?) { val fragment = when (intent?.getStringExtra(KEY_NOTIFICATION_INTENT)) { NOTIFICATION_INTENT_PICTURES -> SettingsPictureUploadsFragment() NOTIFICATION_INTENT_VIDEOS -> SettingsVideoUploadsFragment() else -> SettingsFragment() } supportFragmentManager .beginTransaction() .replace(R.id.settings_container, fragment) .commit() } companion object { const val KEY_NOTIFICATION_INTENT = "key_notification_intent" const val NOTIFICATION_INTENT_PICTURES = "picture_uploads" const val NOTIFICATION_INTENT_VIDEOS = "video_uploads" } }
gpl-2.0
8a1cba7f39c57d2f80111e4eeb202bb7
39.285714
93
0.707225
4.969163
false
false
false
false
google/horologist
base-ui/src/main/java/com/google/android/horologist/base/ui/components/StandardButton.kt
1
2912
/* * 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.google.android.horologist.base.ui.components import androidx.compose.foundation.layout.size import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import androidx.wear.compose.material.Button import androidx.wear.compose.material.ButtonDefaults import androidx.wear.compose.material.Icon import com.google.android.horologist.base.ui.ExperimentalHorologistBaseUiApi /** * This composable fulfils the redlines of the following components: * - Primary, Secondary or Icon only button - according to [buttonType] value; * - Default, Large, Small and Extra Small button - according to [buttonSize] value; */ @ExperimentalHorologistBaseUiApi @Composable public fun StandardButton( imageVector: ImageVector, contentDescription: String, onClick: () -> Unit, modifier: Modifier = Modifier, buttonType: StandardButtonType = StandardButtonType.Primary, buttonSize: StandardButtonSize = StandardButtonSize.Default, enabled: Boolean = true ) { Button( onClick = onClick, modifier = modifier.size(buttonSize.tapTargetSize), enabled = enabled, colors = when (buttonType) { StandardButtonType.Primary -> ButtonDefaults.primaryButtonColors() StandardButtonType.Secondary -> ButtonDefaults.secondaryButtonColors() StandardButtonType.IconOnly -> ButtonDefaults.iconButtonColors() } ) { Icon( imageVector = imageVector, contentDescription = contentDescription, modifier = Modifier .size(buttonSize.iconSize) .align(Alignment.Center) ) } } @ExperimentalHorologistBaseUiApi public enum class StandardButtonType { Primary, Secondary, IconOnly, } @ExperimentalHorologistBaseUiApi public enum class StandardButtonSize( public val iconSize: Dp, public val tapTargetSize: Dp ) { Default(iconSize = 26.dp, tapTargetSize = 52.dp), Large(iconSize = 30.dp, tapTargetSize = 60.dp), Small(iconSize = 24.dp, tapTargetSize = 48.dp), ExtraSmall(iconSize = 24.dp, tapTargetSize = 48.dp), }
apache-2.0
04e3b4a057e4788a4e243d755771c8f1
34.084337
84
0.728709
4.542902
false
false
false
false
google/horologist
media-sample/src/main/java/com/google/android/horologist/mediasample/ui/settings/UampSettingsScreen.kt
1
4488
/* * 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.google.android.horologist.mediasample.ui.settings import androidx.compose.foundation.layout.RowScope import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.DataObject import androidx.compose.material.icons.filled.Logout import androidx.compose.runtime.Composable import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.compose.ui.focus.FocusRequester import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import androidx.navigation.NavHostController import androidx.wear.compose.material.Chip import androidx.wear.compose.material.ChipColors import androidx.wear.compose.material.ChipDefaults import androidx.wear.compose.material.Icon import androidx.wear.compose.material.MaterialTheme import androidx.wear.compose.material.ScalingLazyColumn import androidx.wear.compose.material.ScalingLazyListState import androidx.wear.compose.material.Text import com.google.android.horologist.compose.focus.RequestFocusWhenActive import com.google.android.horologist.compose.rotaryinput.rotaryWithFling import com.google.android.horologist.mediasample.R import com.google.android.horologist.mediasample.ui.navigation.navigateToDeveloperOptions @Composable fun UampSettingsScreen( state: ScalingLazyListState, settingsScreenViewModel: SettingsScreenViewModel, navController: NavHostController, modifier: Modifier = Modifier ) { val focusRequester = remember { FocusRequester() } ScalingLazyColumn( modifier = modifier .fillMaxSize() .rotaryWithFling(focusRequester, state), state = state ) { item { Text( text = stringResource(id = R.string.sample_settings), modifier = Modifier.padding(bottom = 12.dp), style = MaterialTheme.typography.title3 ) } item { ActionSetting( text = stringResource(id = R.string.sample_developer_options), icon = Icons.Default.DataObject, colors = ChipDefaults.secondaryChipColors(), onClick = { navController.navigateToDeveloperOptions() } ) } item { ActionSetting( text = stringResource(id = R.string.logout), icon = Icons.Default.Logout, colors = ChipDefaults.secondaryChipColors(), enabled = false, onClick = { settingsScreenViewModel.logout() } ) } } RequestFocusWhenActive(focusRequester) } @Composable fun ActionSetting( text: String, icon: ImageVector? = null, enabled: Boolean = true, colors: ChipColors = ChipDefaults.primaryChipColors(), onClick: () -> Unit ) { val hasIcon = icon != null val labelParam: (@Composable RowScope.() -> Unit) = { Text( text = text, modifier = Modifier.fillMaxWidth(), textAlign = if (hasIcon) TextAlign.Left else TextAlign.Center, overflow = TextOverflow.Ellipsis, maxLines = 2 ) } Chip( onClick = onClick, label = labelParam, enabled = enabled, modifier = Modifier.fillMaxWidth(), colors = colors, icon = { if (icon != null) { Icon(imageVector = icon, contentDescription = text) } }, contentPadding = ChipDefaults.ContentPadding ) }
apache-2.0
53e66f6982a983f4aaf70b847218893b
34.619048
89
0.687166
4.836207
false
false
false
false
android/camera-samples
Camera2Extensions/app/src/main/java/com/example/android/camera2/extensions/CameraActivity.kt
1
3553
/* * Copyright (C) 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.camera2.extensions import android.Manifest import android.content.pm.PackageManager import android.os.Bundle import android.view.View import android.widget.FrameLayout import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import androidx.activity.result.contract.ActivityResultContracts import androidx.core.content.ContextCompat /* * This is the launching point for the camera extension app where the camera fragment container * is delayed to allow the UI to settle. All of the camera extension code can be found in * "CameraFragment". */ class CameraActivity : AppCompatActivity() { private lateinit var container: FrameLayout private val requestPermissionLauncher = registerForActivityResult( ActivityResultContracts.RequestPermission() ) { isGranted: Boolean -> if (isGranted) { // Before setting full screen flags, we must wait a bit to let UI settle; otherwise, // we may be trying to set app to immersive mode before it's ready and the flags do // not stick container.postDelayed({ @Suppress("DEPRECATION") container.systemUiVisibility = FLAGS_FULLSCREEN }, IMMERSIVE_FLAG_TIMEOUT) } else { Toast.makeText(this, R.string.permission_required, Toast.LENGTH_SHORT).show() finish() } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_camera) container = findViewById(R.id.fragment_container) } override fun onResume() { super.onResume() if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) { container.postDelayed({ @Suppress("DEPRECATION") container.systemUiVisibility = FLAGS_FULLSCREEN }, IMMERSIVE_FLAG_TIMEOUT) } else { requestPermissionLauncher.launch(Manifest.permission.CAMERA) } } companion object { /** Combination of all flags required to put activity into immersive mode */ @Suppress("DEPRECATION") const val FLAGS_FULLSCREEN = View.SYSTEM_UI_FLAG_LOW_PROFILE or View.SYSTEM_UI_FLAG_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY /** Milliseconds used for UI animations */ private const val IMMERSIVE_FLAG_TIMEOUT = 500L } }
apache-2.0
17be9d4fc053e0a39bdb727173a47f42
37.619565
100
0.618632
5.302985
false
false
false
false
tinypass/piano-sdk-for-android
id/id/src/test/java/io/piano/android/id/models/BaseResponseTest.kt
1
976
package io.piano.android.id.models import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFalse import kotlin.test.assertTrue class BaseResponseTest { @Suppress("NOTHING_TO_INLINE") private inline fun makeResponse( code: Int = 0, message: String? = null, validationErrors: Map<String, String>? = null ) = BaseResponse(code, message, validationErrors) @Test fun hasError() { assertTrue { makeResponse(code = 1).hasError } assertFalse { makeResponse(code = 0).hasError } } @Test fun getError() { assertEquals("$MSG; $MSG", makeResponse(validationErrors = mapOf("test" to MSG, "test2" to MSG)).error) assertEquals(MSG, makeResponse(validationErrors = mapOf(BaseResponse.KEY_MESSAGE to MSG)).error) assertEquals("${BaseResponse.ERROR_TEMPLATE}1", makeResponse(code = 1).error) } companion object { const val MSG = "1234" } }
apache-2.0
038a8930013f365e02a95b587f04506b
28.575758
111
0.66291
4.17094
false
true
false
false
Kotlin/dokka
plugins/base/src/test/kotlin/parsers/JavadocParserTest.kt
1
18858
package parsers import com.jetbrains.rd.util.first import org.jetbrains.dokka.base.testApi.testRunner.BaseAbstractTest import org.jetbrains.dokka.links.Callable import org.jetbrains.dokka.links.DRI import org.jetbrains.dokka.links.JavaClassReference import org.jetbrains.dokka.model.DEnum import org.jetbrains.dokka.model.DModule import org.jetbrains.dokka.model.doc.* import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstanceOrNull import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Test import utils.docs import utils.text import kotlin.test.assertNotNull class JavadocParserTest : BaseAbstractTest() { private val configuration = dokkaConfiguration { sourceSets { sourceSet { sourceRoots = listOf("src/") analysisPlatform = "jvm" } } } private fun performJavadocTest(testOperation: (DModule) -> Unit) { val configuration = dokkaConfiguration { sourceSets { sourceSet { sourceRoots = listOf("src/main/java") } } } testInline( """ |/src/main/java/sample/Date2.java | |package docs |/** | * class level docs | */ |public enum AnEnumType { | /** | * content being refreshed, which can be a result of | * invalidation, refresh that may contain content updates, or the initial load. | */ | REFRESH |} """.trimIndent(), configuration ) { documentablesMergingStage = testOperation } } @Test fun `correctly parsed list`() { performJavadocTest { module -> val docs = (module.packages.single().classlikes.single() as DEnum).entries.single().documentation.values.single().children.single().root.text() assertEquals("content being refreshed, which can be a result of invalidation, refresh that may contain content updates, or the initial load.", docs.trimEnd()) } } @Test fun `code tag`() { val source = """ |/src/main/kotlin/test/Test.java |package example | | /** | * Identifies calls to {@code assertThat}. | * | * {@code | * Set<String> s; | * System.out.println("s1 = " + s); | * } | * <pre>{@code | * Set<String> s2; | * System.out | * .println("s2 = " + s2); | * }</pre> | * | */ | public class Test {} """.trimIndent() testInline( source, configuration, ) { documentablesCreationStage = { modules -> val docs = modules.first().packages.first().classlikes.single().documentation.first().value val root = docs.children.first().root kotlin.test.assertEquals( listOf( Text(body = "Identifies calls to "), CodeInline(children = listOf(Text(body = "assertThat"))), Text(body = ". "), CodeInline(children = listOf(Text(body = "\nSet<String> s;\nSystem.out.println(\"s1 = \" + s);\n"))) ), root.children[0].children ) kotlin.test.assertEquals( CodeBlock(children = listOf(Text(body = "\nSet<String> s2;\nSystem.out\n .println(\"s2 = \" + s2);\n"))), root.children[1] ) } } } @Test fun `literal tag`() { val source = """ |/src/main/kotlin/test/Test.java |package example | | /** | * An example of using the literal tag | * {@literal @}Entity | * public class User {} | */ | public class Test {} """.trimIndent() testInline( source, configuration, ) { documentablesCreationStage = { modules -> val docs = modules.first().packages.first().classlikes.single().documentation.first().value val root = docs.children.first().root kotlin.test.assertEquals( listOf( Text(body = "An example of using the literal tag "), Text(body = "@"), Text(body = "Entity public class User {}"), ), root.children.first().children ) } } } @Test fun `literal tag nested under pre tag`() { val source = """ |/src/main/kotlin/test/Test.java |package example | | /** | * An example of using the literal tag | * <pre> | * {@literal @}Entity | * public class User {} | * </pre> | */ | public class Test {} """.trimIndent() testInline( source, configuration, ) { documentablesCreationStage = { modules -> val docs = modules.first().packages.first().classlikes.single().documentation.first().value val root = docs.children.first().root kotlin.test.assertEquals( listOf( P(children = listOf(Text(body = "An example of using the literal tag "))), Pre(children = listOf( Text(body = "@"), Text(body = "Entity\npublic class User {}\n") ) ) ), root.children ) } } } @Test fun `literal tag containing angle brackets`() { val source = """ |/src/main/kotlin/test/Test.java |package example | | /** | * An example of using the literal tag | * {@literal a<B>c} | */ | public class Test {} """.trimIndent() testInline( source, configuration, ) { documentablesCreationStage = { modules -> val docs = modules.first().packages.first().classlikes.single().documentation.first().value val root = docs.children.first().root kotlin.test.assertEquals( listOf( P(children = listOf( Text(body = "An example of using the literal tag "), Text(body = "a<B>c") )), ), root.children ) } } } @Test fun `html img tag`() { val source = """ |/src/main/kotlin/test/Test.java |package example | | /** | * <img src="/path/to/img.jpg" alt="Alt text"/> | */ | public class Test {} """.trimIndent() testInline( source, configuration, ) { documentablesCreationStage = { modules -> val docs = modules.first().packages.first().classlikes.single().documentation.first().value val root = docs.children.first().root kotlin.test.assertEquals( listOf( P( children = listOf( Img( params = mapOf( "href" to "/path/to/img.jpg", "alt" to "Alt text" ) ) ) ) ), root.children ) } } } @Test fun `description list tag`() { val source = """ |/src/main/kotlin/test/Test.java |package example | | /** | * <dl> | * <dt> | * <code>name="<i>name</i>"</code> | * </dt> | * <dd> | * A URI path segment. The subdirectory name for this value is contained in the | * <code>path</code> attribute. | * </dd> | * <dt> | * <code>path="<i>path</i>"</code> | * </dt> | * <dd> | * The subdirectory you're sharing. While the <i>name</i> attribute is a URI path | * segment, the <i>path</i> value is an actual subdirectory name. | * </dd> | * </dl> | */ | public class Test {} """.trimIndent() val expected = listOf( Dl( listOf( Dt( listOf( CodeInline( listOf( Text("name=\""), I( listOf( Text("name") ) ), Text("\"") ) ), ) ), Dd( listOf( Text(" A URI path segment. The subdirectory name for this value is contained in the "), CodeInline( listOf( Text("path") ) ), Text(" attribute. ") ) ), Dt( listOf( CodeInline( listOf( Text("path=\""), I( listOf( Text("path") ) ), Text("\"") ) ) ) ), Dd( listOf( Text(" The subdirectory you're sharing. While the "), I( listOf( Text("name") ) ), Text(" attribute is a URI path segment, the "), I( listOf( Text("path") ) ), Text(" value is an actual subdirectory name. ") ) ) ) ) ) testInline(source, configuration) { documentablesCreationStage = { modules -> val docs = modules.first().packages.first().classlikes.single().documentation.first().value assertEquals(expected, docs.children.first().root.children) } } } @Test fun `header tags are handled properly`() { val source = """ |/src/main/kotlin/test/Test.java |package example | | /** | * An example of using the header tags | * <h1>A header</h1> | * <h2>A second level header</h2> | * <h3>A third level header</h3> | */ | public class Test {} """.trimIndent() testInline( source, configuration, ) { documentablesCreationStage = { modules -> val docs = modules.first().packages.first().classlikes.single().documentation.first().value val root = docs.children.first().root kotlin.test.assertEquals( listOf( P(children = listOf(Text("An example of using the header tags "))), H1( listOf( Text("A header") ) ), H2( listOf( Text("A second level header") ) ), H3( listOf( Text("A third level header") ) ) ), root.children ) } } } @Test fun `var tag is handled properly`() { val source = """ |/src/main/kotlin/test/Test.java |package example | | /** | * An example of using var tag: <var>variable</var> | */ | public class Test {} """.trimIndent() testInline( source, configuration, ) { documentablesCreationStage = { modules -> val docs = modules.first().packages.first().classlikes.single().documentation.first().value val root = docs.children.first().root kotlin.test.assertEquals( listOf( P(children = listOf( Text("An example of using var tag: "), Var(children = listOf(Text("variable"))), )), ), root.children ) } } } @Test fun `u tag is handled properly`() { val source = """ |/src/main/kotlin/test/Test.java |package example | | /** | * An example of using u tag: <u>underlined</u> | */ | public class Test {} """.trimIndent() testInline( source, configuration, ) { documentablesCreationStage = { modules -> val docs = modules.first().packages.first().classlikes.single().documentation.first().value val root = docs.children.first().root assertEquals( listOf( P(children = listOf( Text("An example of using u tag: "), U(children = listOf(Text("underlined"))), )), ), root.children ) } } } @Test fun `undocumented see also from java`(){ testInline( """ |/src/main/java/example/Source.java |package example; | |public interface Source { | String getProperty(String k, String v); | | /** | * @see #getProperty(String, String) | */ | String getProperty(String k); |} """.trimIndent(), configuration ) { documentablesTransformationStage = { module -> val functionWithSeeTag = module.packages.flatMap { it.classlikes }.flatMap { it.functions }.find { it.name == "getProperty" && it.parameters.count() == 1 } val seeTag = functionWithSeeTag?.docs()?.firstIsInstanceOrNull<See>() val expectedLinkDestinationDRI = DRI( packageName = "example", classNames = "Source", callable = Callable( name = "getProperty", params = listOf(JavaClassReference("java.lang.String"), JavaClassReference("java.lang.String")) ) ) assertNotNull(seeTag) assertEquals("getProperty(String, String)", seeTag.name) assertEquals(expectedLinkDestinationDRI, seeTag.address) assertEquals(emptyList<DocTag>(), seeTag.children) } } } @Test fun `documented see also from java`(){ testInline( """ |/src/main/java/example/Source.java |package example; | |public interface Source { | String getProperty(String k, String v); | | /** | * @see #getProperty(String, String) this is a reference to a method that is present on the same class. | */ | String getProperty(String k); |} """.trimIndent(), configuration ) { documentablesTransformationStage = { module -> val functionWithSeeTag = module.packages.flatMap { it.classlikes }.flatMap { it.functions }.find { it.name == "getProperty" && it.parameters.size == 1 } val seeTag = functionWithSeeTag?.docs()?.firstIsInstanceOrNull<See>() val expectedLinkDestinationDRI = DRI( packageName = "example", classNames = "Source", callable = Callable( name = "getProperty", params = listOf(JavaClassReference("java.lang.String"), JavaClassReference("java.lang.String")) ) ) assertNotNull(seeTag) assertEquals("getProperty(String, String)", seeTag.name) assertEquals(expectedLinkDestinationDRI, seeTag.address) assertEquals( "this is a reference to a method that is present on the same class.", seeTag.children.first().text().trim() ) assertEquals(1, seeTag.children.size) } } } }
apache-2.0
35021d70c509426d09d8f02ae4409aa8
33.47532
171
0.398452
5.673285
false
true
false
false
HendraAnggrian/kota
kota/src/collections/SparseIntArrays.kt
1
1719
@file:JvmMultifileClass @file:JvmName("SparseArraysKt") @file:Suppress("NOTHING_TO_INLINE", "UNUSED", "EXTENSION_SHADOWED_BY_MEMBER") package kota import android.util.SparseIntArray import java.util.* /** Transform current map to sparse array. */ inline fun Map<Int, Int>.toSparseIntArray(): SparseIntArray = SparseIntArray().apply { for (key in keys) append(key, get(key)) } /** Returns an empty sparse array. */ inline fun sparseIntArrayOf(): SparseIntArray = SparseIntArray() /** Returns a sparse array with matching position of array input. */ inline fun sparseIntArrayOf(vararg elements: Int): SparseIntArray = SparseIntArray().apply { var i = 0 for (element in elements) append(i++, element) } /** Returns a sparse array with defined position and element from Kotlin pair. */ inline fun sparseIntArrayOf(vararg pairs: Pair<Int, Int>): SparseIntArray = SparseIntArray().apply { for ((key, value) in pairs) append(key, value) } inline operator fun SparseIntArray.get(key: Int): Int = get(key) inline operator fun SparseIntArray.set(key: Int, value: Int) = put(key, value) inline fun SparseIntArray.containsKey(key: Int): Boolean = indexOfKey(key) > -1 inline fun SparseIntArray.containsValue(value: Int): Boolean = indexOfValue(value) > -1 inline fun SparseIntArray.forEach(action: (Int) -> Unit) { val size = size() for (i in 0 until size) { if (size != size()) throw ConcurrentModificationException() action(valueAt(i)) } } inline fun SparseIntArray.forEachIndexed(action: (Int, Int) -> Unit) { val size = size() for (i in 0 until size) { if (size != size()) throw ConcurrentModificationException() action(keyAt(i), valueAt(i)) } }
apache-2.0
914a9bea69c5a76729bfcfbcf5aab662
34.102041
100
0.707388
3.988399
false
false
false
false
vsch/idea-multimarkdown
src/main/java/com/vladsch/md/nav/flex/language/folding/MdFlexmarkFoldingBuilder.kt
1
4197
// Copyright (c) 2017-2020 Vladimir Schneider <[email protected]> Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.vladsch.md.nav.flex.language.folding import com.intellij.lang.folding.FoldingDescriptor import com.intellij.openapi.util.TextRange import com.vladsch.md.nav.flex.PluginBundle import com.vladsch.md.nav.flex.psi.* import com.vladsch.md.nav.language.api.MdFoldingVisitorHandler import com.vladsch.md.nav.psi.util.MdVisitHandler // FLEXMARK_PLUGIN class MdFlexmarkFoldingBuilder(handler: MdFoldingVisitorHandler, @Suppress("UNUSED_PARAMETER") quick: Boolean) : MdFoldingVisitorHandler by handler { init { addHandlers( MdVisitHandler(FlexmarkFrontMatterBlock::class.java, this::fold), MdVisitHandler(FlexmarkExample::class.java, this::fold), MdVisitHandler(FlexmarkExampleSource::class.java, this::fold), MdVisitHandler(FlexmarkExampleHtml::class.java, this::fold), MdVisitHandler(FlexmarkExampleAst::class.java, this::fold) ) } private fun fold(element: FlexmarkFrontMatterBlock) { val range = element.textRange if (!range.isEmpty && range.startOffset + 3 < range.endOffset) { addDescriptor(object : FoldingDescriptor(element.node, TextRange(range.startOffset + 3, range.endOffset), null) { override fun getPlaceholderText(): String? { return defaultPlaceHolderText } }) visitChildren(element) } } private fun fold(element: FlexmarkExampleSource) { if (element.node.textLength > 0) { val textRange = TextRange(element.node.startOffset, element.node.startOffset + element.node.textLength - 1) if (!textRange.isEmpty) { addDescriptor(object : FoldingDescriptor(element.node, textRange, null) { override fun getPlaceholderText(): String? { // FLEXMARK_PLUGIN return defaultPlaceHolderText + PluginBundle.message("code-folding.flexmark.example.source.placeholder") + defaultPlaceHolderText } }) } visitChildren(element) } } private fun fold(element: FlexmarkExampleHtml) { if (element.node.textLength > 0) { val textRange = TextRange(element.node.startOffset, element.node.startOffset + element.node.textLength - 1) if (!textRange.isEmpty) { addDescriptor(object : FoldingDescriptor(element.node, textRange, null) { override fun getPlaceholderText(): String? { // FLEXMARK_PLUGIN return defaultPlaceHolderText + PluginBundle.message("code-folding.flexmark.example.html.placeholder") + defaultPlaceHolderText } }) } visitChildren(element) } } private fun fold(element: FlexmarkExampleAst) { if (element.node.textLength > 0) { val textRange = TextRange(element.node.startOffset, element.node.startOffset + element.node.textLength - 1) if (!textRange.isEmpty) { addDescriptor(object : FoldingDescriptor(element.node, textRange, null) { override fun getPlaceholderText(): String? { // FLEXMARK_PLUGIN return defaultPlaceHolderText + PluginBundle.message("code-folding.flexmark.example.ast.placeholder") + defaultPlaceHolderText } }) } visitChildren(element) } } private fun fold(element: FlexmarkExample) { val exRange = element.foldingRange if (exRange != null && !exRange.isEmpty) { val text = " " + element.presentableText + " ..." addDescriptor(object : FoldingDescriptor(element.node, exRange, null) { override fun getPlaceholderText(): String? { return text } }) visitChildren(element) } } }
apache-2.0
1409f1cd1eef3ffea062efac5efe58a4
43.648936
177
0.616869
4.966864
false
false
false
false
quarkusio/quarkus
extensions/panache/mongodb-panache-kotlin/runtime/src/main/kotlin/io/quarkus/mongodb/panache/kotlin/PanacheMongoCompanion.kt
1
24985
package io.quarkus.mongodb.panache.kotlin import com.mongodb.client.MongoCollection import com.mongodb.client.MongoDatabase import io.quarkus.mongodb.panache.kotlin.runtime.KotlinMongoOperations.Companion.INSTANCE import io.quarkus.panache.common.Parameters import io.quarkus.panache.common.Sort import io.quarkus.panache.common.impl.GenerateBridge import org.bson.Document import org.bson.types.ObjectId import java.util.stream.Stream /** * Define persistence and query methods for an Entity with a default ID type of [ObjectId] * * @param Entity the entity type */ interface PanacheMongoCompanion<Entity : PanacheMongoEntityBase> : PanacheMongoCompanionBase<Entity, ObjectId> /** * Define persistence and query methods for an Entity with a type of Id * * @param Entity the entity type * @param Id the ID type */ interface PanacheMongoCompanionBase<Entity : PanacheMongoEntityBase, Id : Any> { /** * Find an entity of this type by ID. * * @param id the ID of the entity to find. * @return the entity found, or `null` if not found. */ @GenerateBridge(targetReturnTypeErased = true) fun findById(id: Id): Entity? = throw INSTANCE.implementationInjectionMissing() /** * Find entities using a query, with optional indexed parameters. * * @param query a query string * @param params optional sequence of indexed parameters * @return a new [PanacheQuery] instance for the given query * @see [find] * @see [list] * @see [stream] */ @GenerateBridge fun find(query: String, vararg params: Any?): PanacheQuery<Entity> = throw INSTANCE.implementationInjectionMissing() /** * Find entities using a query and the given sort options with optional indexed parameters. * * @param query a query string * @param sort the sort strategy to use * @param params optional sequence of indexed parameters * @return a new [PanacheQuery] instance for the given query * @see [find] * @see [list] * @see [stream] */ @GenerateBridge fun find(query: String, sort: Sort, vararg params: Any?): PanacheQuery<Entity> = throw INSTANCE.implementationInjectionMissing() /** * Find entities using a query, with named parameters. * * @param query a query string * @param params [Map] of named parameters * @return a new [PanacheQuery] instance for the given query * @see [find] * @see [list] * @see [stream] */ @GenerateBridge fun find(query: String, params: Map<String, Any?>): PanacheQuery<Entity> = throw INSTANCE.implementationInjectionMissing() /** * Find entities using a query and the given sort options, with named parameters. * * @param query a query string * @param sort the sort strategy to use * @param params [Map] of indexed parameters * @return a new [PanacheQuery] instance for the given query * @see [find] * @see [list] * @see [stream] */ @GenerateBridge fun find(query: String, sort: Sort, params: Map<String, Any?>): PanacheQuery<Entity> = throw INSTANCE.implementationInjectionMissing() /** * Find entities using a query, with named parameters. * * @param query a query string * @param params Parameters of named parameters * @return a new [PanacheQuery] instance for the given query * @see [find] * @see [list] * @see [stream] */ @GenerateBridge fun find(query: String, params: Parameters): PanacheQuery<Entity> = throw INSTANCE.implementationInjectionMissing() /** * Find entities using a query and the given sort options with named parameters. * * @param query a query string * @param sort the sort strategy to use * @param params Parameters of indexed parameters * @return a new [PanacheQuery] instance for the given query * @see [find] * @see [list] * @see [stream] */ @GenerateBridge fun find(query: String, sort: Sort, params: Parameters): PanacheQuery<Entity> = throw INSTANCE.implementationInjectionMissing() /** * Find entities using a BSON query. * * @param query a query string * @return a new [PanacheQuery] instance for the given query * @see [find] * @see [list] * @see [stream] */ @GenerateBridge fun find(query: Document): PanacheQuery<Entity> = throw INSTANCE.implementationInjectionMissing() /** * Find entities using a BSON query and a BSON sort. * * @param query a query string * @param sort the sort strategy to use * @return a new [PanacheQuery] instance for the given query * @see [find] * @see [list] * @see [stream] */ @GenerateBridge fun find(query: Document, sort: Document): PanacheQuery<Entity> = throw INSTANCE.implementationInjectionMissing() /** * Find all entities of this type. * * @return a new [PanacheQuery] instance to find all entities of this type. * @see [findAll] * @see [listAll] * @see [streamAll] */ @GenerateBridge fun findAll(): PanacheQuery<Entity> = throw INSTANCE.implementationInjectionMissing() /** * Find all entities of this type, in the given order. * * @param sort the sort order to use * @return a new [PanacheQuery] instance to find all entities of this type. * @see [findAll] * @see [listAll] * @see [streamAll] */ @GenerateBridge fun findAll(sort: Sort): PanacheQuery<Entity> = throw INSTANCE.implementationInjectionMissing() /** * Find entities matching a query, with optional indexed parameters. * This method is a shortcut for `find(query, params).list()`. * * @param query a query string * @param params optional sequence of indexed parameters * @return a [List] containing all results, without paging * @see [list] * @see [find] * @see [stream] */ @GenerateBridge fun list(query: String, vararg params: Any?): List<Entity> = throw INSTANCE.implementationInjectionMissing() /** * Find entities matching a query and the given sort options, with optional indexed parameters. * This method is a shortcut for `find(query, sort, params).list()`. * * @param query a query string * @param sort the sort strategy to use * @param params optional sequence of indexed parameters * @return a [List] containing all results, without paging * @see [list] * @see [find] * @see [stream] */ @GenerateBridge fun list(query: String, sort: Sort, vararg params: Any?): List<Entity> = throw INSTANCE.implementationInjectionMissing() /** * Find entities matching a query, with named parameters. * This method is a shortcut for `find(query, params).list()`. * * @param query a query string * @param params [Map] of named parameters * @return a [List] containing all results, without paging * @see [list] * @see [find] * @see [stream] */ @GenerateBridge fun list(query: String, params: Map<String, Any?>): List<Entity> = throw INSTANCE.implementationInjectionMissing() /** * Find entities matching a query and the given sort options, with named parameters. * This method is a shortcut for `find(query, sort, params).list()`. * * @param query a query string * @param sort the sort strategy to use * @param params [Map] of indexed parameters * @return a [List] containing all results, without paging * @see [list] * @see [find] * @see [stream] */ @GenerateBridge fun list(query: String, sort: Sort, params: Map<String, Any?>): List<Entity> = throw INSTANCE.implementationInjectionMissing() /** * Find entities matching a query, with named parameters. * This method is a shortcut for `find(query, params).list()`. * * @param query a query string * @param params Parameters of named parameters * @return a [List] containing all results, without paging * @see [list] * @see [find] * @see [stream] */ @GenerateBridge fun list(query: String, params: Parameters): List<Entity> = throw INSTANCE.implementationInjectionMissing() /** * Find entities matching a query and the given sort options, with named parameters. * This method is a shortcut for `find(query, sort, params).list()`. * * @param query a query string * @param sort the sort strategy to use * @param params Parameters of indexed parameters * @return a [List] containing all results, without paging * @see [list] * @see [find] * @see [stream] */ @GenerateBridge fun list(query: String, sort: Sort, params: Parameters): List<Entity> = throw INSTANCE.implementationInjectionMissing() /** * Find entities using a BSON query. * This method is a shortcut for `find(query).list()`. * * @param query a query document * @return a [List] containing all results, without paging * @see [list] * @see [find] * @see [stream] */ @GenerateBridge fun list(query: Document): List<Entity> = throw INSTANCE.implementationInjectionMissing() /** * Find entities using a BSON query and a BSON sort. * This method is a shortcut for `find(query, sort).list()`. * * @param query a query document * @param sort the sort document * @return a [List] containing all results, without paging * @see [list] * @see [find] * @see [stream] */ @GenerateBridge fun list(query: Document, sort: Document): List<Entity> = throw INSTANCE.implementationInjectionMissing() /** * Find all entities of this type. * This method is a shortcut for `findAll().list()`. * * @return a [List] containing all results, without paging * @see [listAll] * @see [findAll] * @see [streamAll] */ @GenerateBridge fun listAll(): List<Entity> = throw INSTANCE.implementationInjectionMissing() /** * Find all entities of this type, in the given order. * This method is a shortcut for `findAll(sort).list()`. * * @param sort the sort order to use * @return a [List] containing all results, without paging * @see [listAll] * @see [findAll] * @see [streamAll] */ @GenerateBridge fun listAll(sort: Sort): List<Entity> = throw INSTANCE.implementationInjectionMissing() /** * Find entities matching a query, with optional indexed parameters. * This method is a shortcut for `find(query, params).stream()`. * * @param query a query string * @param params optional sequence of indexed parameters * @return a Stream containing all results, without paging * @see [stream] * @see [find] * @see [list] */ @GenerateBridge fun stream(query: String, vararg params: Any?): Stream<Entity> = throw INSTANCE.implementationInjectionMissing() /** * Find entities matching a query and the given sort options, with optional indexed parameters. * This method is a shortcut for `find(query, sort, params).stream()`. * * @param query a query string * @param sort the sort strategy to use * @param params optional sequence of indexed parameters * @return a Stream containing all results, without paging * @see [stream] * @see [find] * @see [list] */ @GenerateBridge fun stream(query: String, sort: Sort, vararg params: Any?): Stream<Entity> = throw INSTANCE.implementationInjectionMissing() /** * Find entities matching a query, with named parameters. * This method is a shortcut for `find(query, params).stream()`. * * @param query a query string * @param params [Map] of named parameters * @return a Stream containing all results, without paging * @see [stream] * @see [find] * @see [list] */ @GenerateBridge fun stream(query: String, params: Map<String, Any?>): Stream<Entity> = throw INSTANCE.implementationInjectionMissing() /** * Find entities matching a query and the given sort options, with named parameters. * This method is a shortcut for `find(query, sort, params).stream()`. * * @param query a query string * @param sort the sort strategy to use * @param params [Map] of indexed parameters * @return a Stream containing all results, without paging * @see [stream] * @see [find] * @see [list] */ @GenerateBridge fun stream(query: String, sort: Sort, params: Map<String, Any?>): Stream<Entity> = throw INSTANCE.implementationInjectionMissing() /** * Find entities matching a query, with named parameters. * This method is a shortcut for `find(query, params).stream()`. * * @param query a query string * @param params Parameters of named parameters * @return a Stream containing all results, without paging * @see [stream] * @see [find] * @see [list] */ @GenerateBridge fun stream(query: String, params: Parameters): Stream<Entity> = throw INSTANCE.implementationInjectionMissing() /** * Find entities matching a query and the given sort options, with named parameters. * This method is a shortcut for `find(query, sort, params).stream()`. * * @param query a query string * @param sort the sort strategy to use * @param params Parameters of indexed parameters * @return a Stream containing all results, without paging * @see [stream] * @see [find] * @see [list] */ @GenerateBridge fun stream(query: String, sort: Sort, params: Parameters): Stream<Entity> = throw INSTANCE.implementationInjectionMissing() /** * Find entities using a BSON query. * This method is a shortcut for `find(query).stream()`. * * @param query a query Document * @return a Stream containing all results, without paging * @see [stream] * @see [find] * @see [list] */ @GenerateBridge fun stream(query: Document): Stream<Entity> = throw INSTANCE.implementationInjectionMissing() /** * Find entities using a BSON query and a BSON sort. * This method is a shortcut for `find(query, sort).stream()`. * * @param query a query Document * @param sort the sort strategy to use * @return a Stream containing all results, without paging * @see [stream] * @see [find] * @see [list] */ @GenerateBridge fun stream(query: Document, sort: Document): Stream<Entity> = throw INSTANCE.implementationInjectionMissing() /** * Find all entities of this type. * This method is a shortcut for `findAll().stream()`. * * @return a Stream containing all results, without paging * @see [streamAll] * @see [findAll] * @see [listAll] */ @GenerateBridge fun streamAll(): Stream<Entity> = throw INSTANCE.implementationInjectionMissing() /** * Find all entities of this type, in the given order. * This method is a shortcut for `findAll(sort).stream()`. * * @param sort the sort order to use * @return a Stream containing all results, without paging * @see [streamAll] * @see [findAll] * @see [listAll] */ @GenerateBridge fun streamAll(sort: Sort): Stream<Entity> = throw INSTANCE.implementationInjectionMissing() /** * Counts the number of this type of entity in the database. * * @return the number of this type of entity in the database. * @see [count] */ @GenerateBridge fun count(): Long = throw INSTANCE.implementationInjectionMissing() /** * Counts the number of this type of entity matching the given query, with optional indexed parameters. * * @param query a query string * @param params optional sequence of indexed parameters * @return the number of entities counted. * @see [count] */ @GenerateBridge fun count(query: String, vararg params: Any?): Long = throw INSTANCE.implementationInjectionMissing() /** * Counts the number of this type of entity matching the given query, with named parameters. * * @param query a query string * @param params [Map] of named parameters * @return the number of entities counted. * @see [count] */ @GenerateBridge fun count(query: String, params: Map<String, Any?>): Long = throw INSTANCE.implementationInjectionMissing() /** * Counts the number of this type of entity matching the given query with named parameters. * * @param query a query string * @param params Parameters of named parameters * @return the number of entities counted. * @see [count] */ @GenerateBridge fun count(query: String, params: Parameters): Long = throw INSTANCE.implementationInjectionMissing() /** * Counts the number of this type of entity matching the given query * * @param query a query document * @return the number of entities counted. * @see [count] */ @GenerateBridge fun count(query: Document): Long = throw INSTANCE.implementationInjectionMissing() /** * Delete all entities of this type from the database. * * @return the number of entities deleted. * @see [delete] */ @GenerateBridge fun deleteAll(): Long = throw INSTANCE.implementationInjectionMissing() /** * Delete all entities of this type matching the given query, with optional indexed parameters. * * @param query a query string * @param params optional sequence of indexed parameters * @return the number of entities deleted. * @see [deleteAll] * @see [delete] */ @GenerateBridge fun delete(query: String, vararg params: Any?): Long = throw INSTANCE.implementationInjectionMissing() /** * Delete all entities of this type matching the given query, with named parameters. * * @param query a query string * @param params [Map] of named parameters * @return the number of entities deleted. * @see [deleteAll] * @see [delete] */ @GenerateBridge fun delete(query: String, params: Map<String, Any?>): Long = throw INSTANCE.implementationInjectionMissing() /** * Delete all entities of this type matching the given query, with named parameters. * * @param query a query string * @param params Parameters of named parameters * @return the number of entities deleted. * @see [deleteAll] * @see [delete] */ @GenerateBridge fun delete(query: String, params: Parameters): Long = throw INSTANCE.implementationInjectionMissing() /** * Delete all entities of this type matching the given query * * @param query a query document * @return the number of entities deleted. * @see [deleteAll] * @see [delete] */ @GenerateBridge fun delete(query: Document): Long = throw INSTANCE.implementationInjectionMissing() /** * Delete an entity of this type by ID. * * @param id the ID of the entity to delete. * @return false if the entity was not deleted (not found). */ @GenerateBridge fun deleteById(id: Id): Boolean = throw INSTANCE.implementationInjectionMissing() /** * Insert all given entities. * * @param entities the entities to insert * @see [persist] */ fun persist(entities: Iterable<Entity>) = INSTANCE.persist(entities) /** * Insert all given entities. * * @param entities the entities to insert * @see [persist] */ fun persist(entities: Stream<Entity>) = INSTANCE.persist(entities) /** * Insert all given entities. * * @param entities the entities to insert * @see [persist] */ fun persist(firstEntity: Entity, vararg entities: Entity) = INSTANCE.persist(firstEntity, *entities) /** * Update all given entities. * * @param entities the entities to update * @see [update] */ fun update(entities: Iterable<Entity>) = INSTANCE.update(entities) /** * Update all given entities. * * @param entities the entities to insert * @see [update] */ fun update(entities: Stream<Entity>) = INSTANCE.update(entities) /** * Update all given entities. * * @param entities the entities to update * @see [update] */ fun update(firstEntity: Entity, vararg entities: Entity) = INSTANCE.update(firstEntity, *entities) /** * Persist all given entities or update them if they already exist. * * @param entities the entities to update * @see [persistOrUpdate] */ fun persistOrUpdate(entities: Iterable<Entity>) = INSTANCE.persistOrUpdate(entities) /** * Persist all given entities. * * @param entities the entities to insert * @see [persistOrUpdate] */ fun persistOrUpdate(entities: Stream<Entity>) = INSTANCE.persistOrUpdate(entities) /** * Persist all given entities. * * @param entities the entities to update * @see [persistOrUpdate] */ fun persistOrUpdate(firstEntity: Entity, vararg entities: Entity) = INSTANCE.persistOrUpdate(firstEntity, *entities) /** * Update all entities of this type using the given update document with optional indexed parameters. * The returned [io.quarkus.mongodb.panache.common.PanacheUpdate] object will allow to restrict on which document the update should be applied. * * @param update the update document, if it didn't contain any update operator, we add `$set`. * It can also be expressed as a query string. * @param params optional sequence of indexed parameters * @return a new [io.quarkus.mongodb.panache.common.PanacheUpdate] instance for the given update document * @see [update] */ @GenerateBridge fun update(update: String, vararg params: Any?): io.quarkus.mongodb.panache.common.PanacheUpdate = throw INSTANCE.implementationInjectionMissing() /** * Update all entities of this type by the given update document with named parameters. * The returned [io.quarkus.mongodb.panache.common.PanacheUpdate] object will allow to restrict on which document the update should be applied. * * @param update the update document, if it didn't contain any update operator, we add `$set`. * It can also be expressed as a query string. * * @param params map of named parameters * @return a new [io.quarkus.mongodb.panache.common.PanacheUpdate] instance for the given update document * @see [update] */ @GenerateBridge fun update(update: String, params: Map<String, Any?>): io.quarkus.mongodb.panache.common.PanacheUpdate = throw INSTANCE.implementationInjectionMissing() /** * Update all entities of this type by the given update document, with named parameters. * The returned [io.quarkus.mongodb.panache.common.PanacheUpdate] object will allow to restrict on which document the update should be applied. * * @param update the update document, if it didn't contain any update operator, we add `$set`. * It can also be expressed as a query string. * * @param params [Parameters] of named parameters * @return a new [io.quarkus.mongodb.panache.common.PanacheUpdate] instance for the given update document * @see [update] */ @GenerateBridge fun update(update: String, params: Parameters): io.quarkus.mongodb.panache.common.PanacheUpdate = throw INSTANCE.implementationInjectionMissing() /** * Update all entities of this type by the given update BSON document. * The returned [io.quarkus.mongodb.panache.common.PanacheUpdate] object will allow to restrict on which document the update should be applied. * * @param update the update document, as a [Document]. * @return a new [io.quarkus.mongodb.panache.common.PanacheUpdate] instance for the given update document * @see [update] */ @GenerateBridge fun update(update: Document): io.quarkus.mongodb.panache.common.PanacheUpdate = throw INSTANCE.implementationInjectionMissing() /** * Allow to access the underlying Mongo Collection. * * @return the [MongoCollection] used by this entity */ @GenerateBridge fun mongoCollection(): MongoCollection<Entity> = throw INSTANCE.implementationInjectionMissing() /** * Allow to access the underlying Mongo Database. * * @return the [MongoDatabase] used by this entity */ @GenerateBridge fun mongoDatabase(): MongoDatabase = throw INSTANCE.implementationInjectionMissing() }
apache-2.0
c07a05ccdb212207342584e563b13b24
34.042076
150
0.654473
4.353546
false
false
false
false
uber/RIBs
android/demos/compose/src/main/kotlin/com/uber/rib/compose/util/EventStream.kt
1
971
/* * Copyright (C) 2021. Uber Technologies * * 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.uber.rib.compose.util import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.asSharedFlow class EventStream<T> { private val _sharedFlow = MutableSharedFlow<T>(extraBufferCapacity = 1) private val sharedFlow = _sharedFlow.asSharedFlow() fun notify(event: T) = _sharedFlow.tryEmit(event) fun observe() = sharedFlow }
apache-2.0
c9df7466a0d8d4e820ef9eb954505fd8
33.678571
75
0.752832
4.079832
false
false
false
false
pabiagioli/gopro-showcase
app/src/main/java/com/aajtech/mobile/goproshowcase/GoProPhotosFragment.kt
1
8813
package com.aajtech.mobile.goproshowcase import android.content.Context import android.content.Intent import android.net.Uri import android.os.Bundle import android.speech.RecognitionListener import android.speech.RecognizerIntent import android.speech.SpeechRecognizer import android.support.design.widget.Snackbar import android.support.v4.app.Fragment import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.aajtech.mobile.goproshowcase.dto.GoProSecondaryModes import com.aajtech.mobile.goproshowcase.dto.GoProShutterModes import com.aajtech.mobile.goproshowcase.service.GoProSecondaryModeService import com.aajtech.mobile.goproshowcase.service.GoProShutterService import com.aajtech.mobile.goproshowcase.service.retrofit import com.aajtech.mobile.goproshowcase.service.sendWoL import kotlinx.android.synthetic.main.fragment_photos.* import kotlin.concurrent.thread /** * A simple [Fragment] subclass. * Activities that contain this fragment must implement the * [GoProPhotosFragment.OnFragmentInteractionListener] interface * to handle interaction events. * Use the [GoProPhotosFragment.newInstance] factory method to * create an instance of this fragment. */ class GoProPhotosFragment : Fragment() { // TODO: Rename and change types of parameters private var mParam1: String? = null private var mParam2: String? = null private var mListener: OnFragmentInteractionListener? = null var sr: SpeechRecognizer? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) if (arguments != null) { mParam1 = arguments.getString(ARG_PARAM1) mParam2 = arguments.getString(ARG_PARAM2) } sr = SpeechRecognizer.createSpeechRecognizer(this.context) sr?.setRecognitionListener(srListener) } override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? { // Inflate the layout for this fragment return inflater!!.inflate(R.layout.fragment_photos, container, false) } // TODO: Rename method, update argument and hook method into UI event fun onButtonPressed(uri: Uri) { if (mListener != null) { mListener!!.onFragmentInteraction(uri) } } override fun onResume() { super.onResume() photo_manual_listen.setOnClickListener { val intent = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH) intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM) //intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, "voice.recognition.test") intent.putExtra(RecognizerIntent.EXTRA_PREFER_OFFLINE,true) intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 5) sr?.startListening(intent) } photo_manual_trigger.setOnClickListener { thread { takeSinglePhotoRunnable.run() } } } override fun onAttach(context: Context?) { super.onAttach(context) if (context is OnFragmentInteractionListener) { mListener = context as OnFragmentInteractionListener? } else { throw RuntimeException(context!!.toString() + " must implement OnFragmentInteractionListener") } } override fun onDetach() { super.onDetach() mListener = null } override fun onDestroy() { super.onDestroy() sr?.destroy() val refWatcher = GoProShowcaseApplication.getRefWatcher(activity) refWatcher.watch(this) } /** * This interface must be implemented by activities that contain this * fragment to allow an interaction in this fragment to be communicated * to the activity and potentially other fragments contained in that * activity. * * * See the Android Training lesson [Communicating with Other Fragments](http://developer.android.com/training/basics/fragments/communicating.html) for more information. */ interface OnFragmentInteractionListener { // TODO: Update argument type and name fun onFragmentInteraction(uri: Uri) } val takeSinglePhotoRunnable = object : Runnable { override fun run() { sendWoL() //val primaryMode = retrofit.create(GoProPrimaryModeService::class.java) //var response = primaryMode.setPrimaryMode(GoProPrimaryModes.PHOTO.mode).execute() //if (!response.isSuccessful && response.code() == 500) // response = primaryMode.setPrimaryMode(GoProPrimaryModes.PHOTO.mode).execute() //assert(response.isSuccessful) //Log.d(this.javaClass.name,response.body().string()) val secondaryMode = retrofit.create(GoProSecondaryModeService::class.java) var response2 = secondaryMode.setSubMode( GoProSecondaryModes.SINGLE_PHOTO.mode, GoProSecondaryModes.SINGLE_PHOTO.subMode).execute() //assert(response2.isSuccessful) if (!response2.isSuccessful && response2.code() == 500) response2 = secondaryMode.setSubMode( GoProSecondaryModes.SINGLE_PHOTO.mode, GoProSecondaryModes.SINGLE_PHOTO.subMode).execute() if(response2.isSuccessful) Log.d(this.javaClass.name, response2?.body()?.string()) val trigger = retrofit.create(GoProShutterService::class.java) val response3 = trigger.shutterToggle(GoProShutterModes.TRIGGER_SHUTTER.mode).execute() //assert(response3.isSuccessful) if(response3.isSuccessful) Log.d(this.javaClass.name,response3?.body()?.string()) } } val srListener = object : RecognitionListener { override fun onRmsChanged(rmsdB: Float) { } override fun onEndOfSpeech() { } override fun onReadyForSpeech(params: Bundle?) { Log.d(javaClass.name,"onReadyForSpeech") Snackbar.make(photos_frame_layout, "dale trigo! ", Snackbar.LENGTH_SHORT).show() } override fun onBufferReceived(buffer: ByteArray?) { } override fun onPartialResults(partialResults: Bundle?) { } override fun onEvent(eventType: Int, params: Bundle?) { } override fun onBeginningOfSpeech() { } override fun onError(error: Int) { Log.d(javaClass.name,"Error: $error") Snackbar.make(photos_frame_layout,"Error $error",Snackbar.LENGTH_LONG).show() } override fun onResults(results: Bundle?) { var str = String() Log.d(javaClass.name, "onResults " + results) val data = results?.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION) try { for (i in 0..data?.size?.minus(1)!!) { Log.d(javaClass.name, "result " + data!![i]) Snackbar.make(photos_frame_layout, "results: " + data[i], Snackbar.LENGTH_LONG).show() str += data[i] } //mText.setText("results: " + String.valueOf(data.size())) Snackbar.make(photos_frame_layout, "results: " + data?.size, Snackbar.LENGTH_LONG).show() if (str.contains("snap", true) || str.contains("photo", true)) thread { takeSinglePhotoRunnable.run() } //photo_manual_trigger.performClick() }catch (e:Exception){ Snackbar.make(photos_frame_layout, "hubo un error sarpado", Snackbar.LENGTH_LONG).show() } } } companion object { // TODO: Rename parameter arguments, choose names that match // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private val ARG_PARAM1 = "param1" private val ARG_PARAM2 = "param2" /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * @param param1 Parameter 1. * * * @param param2 Parameter 2. * * * @return A new instance of fragment GoProPhotosFragment. */ // TODO: Rename and change types and number of parameters fun newInstance(param1: String, param2: String): GoProPhotosFragment { val fragment = GoProPhotosFragment() val args = Bundle() args.putString(ARG_PARAM1, param1) args.putString(ARG_PARAM2, param2) fragment.arguments = args return fragment } } }// Required empty public constructor
gpl-3.0
4121fd9a5315b2db3c4466fd19e5efed
37.823789
172
0.648587
4.590104
false
false
false
false
tutao/tutanota
app-android/app/src/main/java/de/tutao/tutanota/Contact.kt
1
1281
package de.tutao.tutanota import android.Manifest import android.provider.ContactsContract import android.provider.ContactsContract.CommonDataKinds.Email import de.tutao.tutanota.ipc.NativeContact /** * Created by mpfau on 4/12/17. */ class Contact(private val activity: MainActivity) { suspend fun findSuggestions(queryString: String): List<NativeContact> { activity.getPermission(Manifest.permission.READ_CONTACTS) val query = "%$queryString%" val resolver = activity.applicationContext.contentResolver val selection = Email.ADDRESS + " LIKE ? OR " + ContactsContract.Contacts.DISPLAY_NAME_PRIMARY + " LIKE ?" val cursor = resolver.query(Email.CONTENT_URI, PROJECTION, selection, arrayOf(query, query), ContactsContract.Contacts.DISPLAY_NAME_PRIMARY + " ASC ") val result = mutableListOf<NativeContact>() return if (cursor == null) { result } else { try { while (cursor.moveToNext()) { val c = NativeContact( name = cursor.getString(1), mailAddress = cursor.getString(2) ) result.add(c) } } finally { cursor.close() } result } } companion object { private val PROJECTION = arrayOf( ContactsContract.Contacts._ID, ContactsContract.Contacts.DISPLAY_NAME_PRIMARY, Email.ADDRESS) } }
gpl-3.0
b9df6a1eff424c2d5d413a241c0adaaa
26.869565
152
0.717408
3.789941
false
false
false
false
google/kiosk-app-reference-implementation
app/src/main/java/com/ape/apps/sample/baypilot/data/sharedprefs/SharedPreferencesManager.kt
1
4279
/* * Copyright 2022 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ape.apps.sample.baypilot.data.sharedprefs import android.content.Context import android.content.SharedPreferences import com.ape.apps.sample.baypilot.data.creditplan.CreditPlanInfo import com.ape.apps.sample.baypilot.data.creditplan.CreditPlanType class SharedPreferencesManager(context: Context) { companion object { private const val TAG = "BayPilotSharedPreferencesManager" private const val SHARED_PREFS = "shared_prefs" private const val KEY_IS_FIRST_RUN = "is_first_run" private const val KEY_IMEI = "imei" private const val KEY_CREDIT_PLAN_SAVED = "credit_plan_saved" private const val KEY_VALID_CREDIT_PLAN = "valid_credit_plan" private const val KEY_DEVICE_RELEASED = "device_released" // Used to observe changes; creditPlanSaveId = lastCreditPlanSaveId + 1 const val KEY_CREDIT_PLAN_SAVE_ID = "credit_plan_save_id" private const val KEY_TOTAL_AMOUNT = "total_amount" private const val KEY_PAID_AMOUNT = "paid_amount" private const val KEY_DUE_DATE = "due_date" private const val KEY_NEXT_DUE_AMOUNT = "next_due_amount" private const val KEY_PLAN_TYPE = "plan_type" } var sharedPreferences: SharedPreferences = context.getSharedPreferences(SHARED_PREFS, Context.MODE_PRIVATE) fun isFirstRun(): Boolean = sharedPreferences.getBoolean(KEY_IS_FIRST_RUN, true) fun writeFirstRun(firstRun: Boolean) = with(sharedPreferences.edit()) { putBoolean(KEY_IS_FIRST_RUN, firstRun) commit() } fun readIMEI(): String = sharedPreferences.getString(KEY_IMEI, "") ?: "" fun writeIMEI(imei: String) = with(sharedPreferences.edit()) { putString(KEY_IMEI, imei) commit() } fun isCreditPlanSaved(): Boolean = sharedPreferences.getBoolean(KEY_CREDIT_PLAN_SAVED, false) fun isValidCreditPlan(): Boolean = sharedPreferences.getBoolean(KEY_VALID_CREDIT_PLAN, false) fun isDeviceReleased(): Boolean = sharedPreferences.getBoolean(KEY_DEVICE_RELEASED, false) fun markDeviceReleased() = with(sharedPreferences.edit()) { incrementCreditPlanSaveId() putBoolean(KEY_DEVICE_RELEASED, true) commit() } fun setCreditPlanInvalid() = with(sharedPreferences.edit()) { incrementCreditPlanSaveId() putBoolean(KEY_CREDIT_PLAN_SAVED, true) putBoolean(KEY_VALID_CREDIT_PLAN, false) commit() } fun readCreditPlan(): CreditPlanInfo? { if (sharedPreferences.getBoolean(KEY_CREDIT_PLAN_SAVED, false).not()) return null if (sharedPreferences.getBoolean(KEY_VALID_CREDIT_PLAN, false).not()) return null return CreditPlanInfo( sharedPreferences.getInt(KEY_TOTAL_AMOUNT, 0), sharedPreferences.getInt(KEY_PAID_AMOUNT, 0), sharedPreferences.getString(KEY_DUE_DATE, ""), sharedPreferences.getInt(KEY_NEXT_DUE_AMOUNT, 0), CreditPlanType.toCreditPlanType(sharedPreferences.getString(KEY_PLAN_TYPE, "")) ) } fun writeCreditPlan(creditPlanInfo: CreditPlanInfo) = with(sharedPreferences.edit()) { incrementCreditPlanSaveId() putBoolean(KEY_CREDIT_PLAN_SAVED, true) putBoolean(KEY_VALID_CREDIT_PLAN, true) putInt(KEY_TOTAL_AMOUNT, creditPlanInfo.totalAmount ?: 0) putInt(KEY_PAID_AMOUNT, creditPlanInfo.totalPaidAmount ?: 0) putString(KEY_DUE_DATE, creditPlanInfo.dueDate ?: "") putInt(KEY_NEXT_DUE_AMOUNT, creditPlanInfo.nextDueAmount ?: 0) putString(KEY_PLAN_TYPE, CreditPlanType.toString(creditPlanInfo.planType) ?: "") commit() } // Used to observe changes; creditPlanSaveId = lastCreditPlanSaveId + 1 private fun SharedPreferences.Editor.incrementCreditPlanSaveId() { putInt(KEY_CREDIT_PLAN_SAVE_ID, sharedPreferences.getInt(KEY_CREDIT_PLAN_SAVE_ID, 0) + 1) } }
apache-2.0
e67ad58fac6a655bd23123628c1bc69d
36.54386
109
0.737322
3.861913
false
false
false
false
ut-iais/java-utils
src/main/java/ir/iais/utilities/javautils/services/db/ScrollableResultsAdaptor.kt
2
1625
///* // * To change this template, choose Tools | Templates // * and open the template in the editor. // */ //package ir.iais.utilities.javautils.services.db // //import ir.iais.utilities.javautils.services.db.interfaces.IScrollable //import org.hibernate.ScrollableResults //import javax.persistence.Entity // ///** @author yoones // */ //class ScrollableResultsAdaptor<out T>(private var scrollableResults: ScrollableResults) : IScrollable<T> { // private var currentObj: T? = null // private var nextCalled: Boolean = true // private var reachedEnd: Boolean = false // private var hasEntityAnnot: Boolean? = null // // @Suppress("UNCHECKED_CAST") // override fun hasNext(): Boolean { // if (nextCalled) { // nextCalled = false // if (scrollableResults.next()) { // val tempObj = scrollableResults.get() // if (tempObj.size == 1 && hasEntityAnnot(tempObj[0])) // currentObj = tempObj[0]!! as T // else // currentObj = tempObj!! as T // fake type casting // return true // } // reachedEnd = true // } // return (!reachedEnd) // } // // override fun next(): T { // nextCalled = true // return currentObj!! // } // // override fun close() { // scrollableResults.close() // } // // private fun hasEntityAnnot(tempObj: Any): Boolean { // if (hasEntityAnnot == null) // hasEntityAnnot = tempObj.javaClass.isAnnotationPresent(Entity::class.java) // return hasEntityAnnot!! // } //}
gpl-3.0
3947cab8c36437592de247cd40c59608
31.5
108
0.584
3.77907
false
false
false
false
jenjinstudios/spritify
spritify-core/src/main/kotlin/com/jenjinstudios/spritify/io/SpriteSheetConfigReaders.kt
1
8511
@file:JvmName("SpriteSheetReaders") package com.jenjinstudios.spritify.io import com.github.salomonbrys.kotson.* import com.google.gson.GsonBuilder import com.google.gson.JsonParseException import com.google.gson.stream.JsonReader import com.jenjinstudios.spritify.* import java.io.InputStream import java.io.InputStreamReader import java.util.* /** * Used to read a `Map` of [sprite sheets][SpriteSheetConfig] from a stream or other serialized form. */ interface SpriteSheetConfigReader { /** * Read a `Map` of [sprite sheets][SpriteSheetConfig]. * * @return The `Map` of [sprite sheets][SpriteSheetConfig] that have been read, where the keys of the `Map` are the names * of the sprite sheets, and the values are the [SpriteSheetConfig] objects themselves. */ fun read(): Map<String, SpriteSheetConfig> /** * Closes this reader and any resources associated with it. */ fun close() } /** * A [SpriteSheetConfigReader] that reads JSON from an `InputStream` and deserializes it into a [SpriteSheetConfig]. * * The data should be formatted as per the following example: * * ``` * [ * { * "id": "UniqueSpritesheetName", * "drawOrder": 0, * "sprites": [ * { * "type": "block", * "duration": 1.0, * "direction": "north", * "action": "walk", * "animation": { * "fileName": "someFile.png", * "frameCount": 4, * "x": 0, * "y": 0, * "width": 128, * "height": 64 * } * }, * { * "type": "segmented", * "duration": 1.0, * "direction": "north", * "action": "idle", * "frames": [ * { * "fileName": "someFile.png", * "x": 0, * "y": 0, * "width": 32, * "height": 64 * }, * { * "fileName": "anotherFile.png", * "x": 32, * "y": 64, * "width": 32, * "height": 64 * } * ] * } * ] * } * ] * ``` * * *`id` is a unique identifier for each [SpriteSheetConfig]. This *must* be unique across *all* sprite sheets in your application. * * `drawOrder` is the order in which the sprite sheet should be drawn to the screen. Sprite sheets with lower values are drawn first, meaning that they appear "below" sprites with higher values when combined. * * `sprites` is an array of objects which define how to create [sprites][SpriteConfig]. * * Each of the elements in this array *must* have `type`, [`duration`][SpriteConfig.duration], [`direction`][SpriteConfig.direction] and [`action`][SpriteConfig.action] properties. * * There are two valid `type` properties * 1. `block`, which tells the reader to create [frames][FrameConfig] based on an entire "row" of an image file * * The `animation` object (which must be present) defines the image file where the sprite is located (defined by the [`fileName`][FrameConfig.fileName] property), and how to create [frames][FrameConfig] from it * * The "row" is defined by `x` and `y` (the top-left corner of the row in the image) as well as `width` and `height` (which dictate how large *the entire row* is in the image. * * The defined "row" is then sliced into a number (defined by `frameCount`) of equal-width blocks which constitute the [frames][FrameConfig]. * 2. `segmented`, which tells the reader to create each [frame][FrameConfig] individually based on the `frames` array. * * Each element in the `frames` array must have the following properties: * * [`fileName`][FrameConfig.fileName] - Points to the image file containing the frame. * * [`x`][FrameConfig.x] and [`y`][FrameConfig.y] - Specify the top-left corner of the frame in the image file. * * [`width`][FrameConfig.width] and [`height`][FrameConfig.height] - Specify the width and height of the frame, in pixels. * * * @param stream The `InputStream` from which to read the JSON data. */ class JsonSpriteSheetConfigReader(stream: InputStream) : SpriteSheetConfigReader { private val jsonReader = JsonReader(InputStreamReader(stream)) override fun read(): Map<String, SpriteSheetConfig> { val gson = GsonBuilder() .registerTypeAdapter<SpriteConfig>(spriteConfigDeserializer) .registerTypeAdapter<SpriteSheetConfig>(spriteSheetDeserializer) .create()!! val spriteSheetsConfig:MutableMap<String, SpriteSheetConfig> = HashMap() jsonReader.beginArray() while(jsonReader.hasNext()) { val spriteSheetConfig = gson.fromJson<SpriteSheetConfig>(jsonReader) spriteSheetsConfig[spriteSheetConfig.id] = spriteSheetConfig } jsonReader.endArray() return spriteSheetsConfig } override fun close() = jsonReader.close() private val spriteSheetDeserializer = jsonDeserializer { val id = it.json["id"].asString ?: missingExpectedProperty("id") val drawOrder = it.json["drawOrder"].asInt val spriteArray = it.json["sprites"].asJsonArray ?: missingExpectedProperty("sprites") val sprites = it.context.deserialize<List<SpriteConfig>>(spriteArray) ?: throw JsonParseException("Unable to parse sprites") val builder = ListSpriteSheetConfigBuilder() sprites.forEach { builder += it } builder.build(id, drawOrder) } private val spriteConfigDeserializer = jsonDeserializer { val type = it.json["type"].asString ?: missingExpectedProperty("type") when(type) { "block" -> readBlockConfiguration(it) "segmented" -> readSegmentedConfiguration(it) else -> throw JsonParseException("Invalid \"type\" property: $type") } } private fun JsonSpriteSheetConfigReader.readSegmentedConfiguration(it: DeserializerArg): SpriteConfig { val duration = it.json["duration"].asFloat val directionString = it.json["direction"].asString ?: missingExpectedProperty("direction") val action = it.json["action"].asString ?: missingExpectedProperty("action") val framesJson = it.json["frames"].asJsonArray ?: missingExpectedProperty("frames") val frames: MutableList<FrameConfig> = LinkedList() framesJson.forEach { val fileName = it["fileName"].asString ?: missingExpectedProperty("fileName") val x = it["x"].asInt val y = it["y"].asInt val width = it["width"].asInt val height = it["height"].asInt frames += FrameConfig(fileName, x, y, width, height) } val direction: Direction try { direction = Direction.valueOf(directionString.toUpperCase()) }catch (e: IllegalArgumentException) { throw JsonParseException("Invalid direction: $directionString") } return SpriteConfig(frames, duration, direction, action) } private fun JsonSpriteSheetConfigReader.readBlockConfiguration(it: DeserializerArg): SpriteConfig { val duration = it.json["duration"].asFloat val directionString = it.json["direction"].asString ?: missingExpectedProperty("direction") val action = it.json["action"].asString ?: missingExpectedProperty("action") val animation = it.json["animation"].asJsonObject ?: missingExpectedProperty("animation") val fileName = animation["fileName"].asString ?: missingExpectedProperty("fileName") val frameCount = animation["frameCount"].asInt val x = animation["x"].asInt val y = animation["y"].asInt val width = animation["width"].asInt val height = animation["height"].asInt val frames: MutableList<FrameConfig> = LinkedList() for (i in 0 until frameCount) { val frameWidth = width / frameCount frames += FrameConfig(fileName, x + (i * frameWidth), y, frameWidth, height) } val direction: Direction try { direction = Direction.valueOf(directionString.toUpperCase()) }catch (e: IllegalArgumentException) { throw JsonParseException("Invalid direction: $directionString") } return SpriteConfig(frames, duration, direction, action) } private fun <T> missingExpectedProperty(name: String): T = throw JsonParseException("Expected $name property") }
mit
569b17c2faf79268a09428ccefadbe6e
40.926108
218
0.635061
4.340133
false
true
false
false
tokenbrowser/token-android-client
app/src/main/java/com/toshi/viewModel/GroupSetupViewModel.kt
1
3633
/* * Copyright (c) 2017. Toshi Inc * * 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.toshi.viewModel import android.arch.lifecycle.MutableLiveData import android.arch.lifecycle.ViewModel import android.graphics.Bitmap import android.net.Uri import com.toshi.util.identicon.createIdenticon import com.toshi.model.local.Conversation import com.toshi.model.local.Group import com.toshi.model.local.User import com.toshi.util.ImageUtil import com.toshi.util.SingleLiveEvent import com.toshi.view.BaseApplication import rx.android.schedulers.AndroidSchedulers import rx.subscriptions.CompositeSubscription class GroupSetupViewModel : ViewModel() { private val chatManager by lazy { BaseApplication.get().chatManager } private val userManager by lazy { BaseApplication.get().userManager } private val subscriptions by lazy { CompositeSubscription() } val conversationCreated by lazy { SingleLiveEvent<Conversation>() } val group by lazy { SingleLiveEvent<Group>() } val error by lazy { SingleLiveEvent<Throwable>() } val isCreatingGroup by lazy { MutableLiveData<Boolean>() } var selectedParticipants: List<User>? = null var avatarUri: Uri? = null fun createGroup(participants: List<User>, avatarUri: Uri?, groupName: String) { if (isCreatingGroup.value == true) return val subscription = generateAvatarFromUri(avatarUri) .map { avatar -> tryGeneratePlaceholderAvatar(avatar, groupName) } .map { avatar -> createGroupObject(participants, avatar, groupName) } .flatMap { addCurrentUserToGroup(it) } .flatMap { createConversationFromGroup(it) } .observeOn(AndroidSchedulers.mainThread()) .doOnSubscribe { isCreatingGroup.value = true } .doAfterTerminate { isCreatingGroup.value = false } .subscribe( { conversationCreated.value = it }, { error.value = it } ) this.subscriptions.add(subscription) } private fun createGroupObject(participants: List<User>, avatar: Bitmap?, groupName: String): Group { return Group(participants) .setTitle(groupName) .setAvatar(avatar) } private fun addCurrentUserToGroup(group: Group) = userManager.getCurrentUser().map { group.addMember(it) } private fun createConversationFromGroup(group: Group) = chatManager.createConversationFromGroup(group) private fun generateAvatarFromUri(avatarUri: Uri?) = ImageUtil.loadAsBitmap(avatarUri, BaseApplication.get()) private fun tryGeneratePlaceholderAvatar(avatar: Bitmap?, groupName: String): Bitmap { return avatar.let { avatar } ?: createIdenticon(groupName) } override fun onCleared() { super.onCleared() subscriptions.clear() } }
gpl-3.0
8ff028e2feb3718c4f89130e399bef03
40.284091
113
0.676576
4.83755
false
false
false
false
tomatrocho/insapp-android
app/src/main/java/fr/insapp/insapp/fragments/SettingsFragment.kt
2
8718
package fr.insapp.insapp.fragments import android.content.Context import android.content.Intent import android.content.SharedPreferences import android.os.Bundle import android.util.Log import android.widget.Toast import androidx.preference.Preference import androidx.preference.PreferenceFragmentCompat import androidx.preference.PreferenceManager import androidx.preference.PreferenceScreen import com.google.gson.Gson import fr.insapp.insapp.App import fr.insapp.insapp.R import fr.insapp.insapp.http.ServiceGenerator import fr.insapp.insapp.models.User import fr.insapp.insapp.notifications.MyFirebaseMessagingService import fr.insapp.insapp.utility.Utils import retrofit2.Call import retrofit2.Callback import retrofit2.Response /** * Created by thomas on 17/07/2017. */ class SettingsFragment : PreferenceFragmentCompat(), SharedPreferences.OnSharedPreferenceChangeListener { override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) { setPreferencesFromResource(R.xml.preferences, rootKey) val defaultSharedPreferences = PreferenceManager.getDefaultSharedPreferences(App.getAppContext()) val barcode = defaultSharedPreferences.getString("barcode", "") if (!barcode.isNullOrEmpty()) { findPreference<Preference>("barcode_fragment")?.summary = barcode } val systemNotifications = findPreference<PreferenceScreen>("notifications_system") systemNotifications?.onPreferenceClickListener = Preference.OnPreferenceClickListener { val intent = Intent() intent.action = "android.settings.APP_NOTIFICATION_SETTINGS" //for Android 5-7 intent.putExtra("app_package", activity?.packageName) intent.putExtra("app_uid", activity?.applicationInfo?.uid) // for Android 8 and above intent.putExtra("android.provider.extra.APP_PACKAGE", activity?.packageName) startActivity(intent) true } } override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences, key: String) { when (key) { "name", "gender", "email", "description" -> { val value = sharedPreferences.getString(key, "") Log.d(TAG, "$key has changed and is now $value") val user = Utils.user if (user != null) { val updatedUser = User( user.id, sharedPreferences.getString("name", "") ?: "", user.username, sharedPreferences.getString("description", "") ?: "", sharedPreferences.getString("email", "") ?: "", user.isEmailPublic, sharedPreferences.getString("class", "") ?: "", sharedPreferences.getString("gender", "") ?: "", user.events, user.postsLiked) val call = ServiceGenerator.client.updateUser(user.id, updatedUser) call.enqueue(object : Callback<User> { override fun onResponse(call: Call<User>, response: Response<User>) { val user = response.body() if (response.isSuccessful && user != null) { val userPreferences = App.getAppContext().getSharedPreferences("User", Context.MODE_PRIVATE) userPreferences.edit().putString("user", Gson().toJson(user)).apply() } else { Toast.makeText(App.getAppContext(), TAG, Toast.LENGTH_LONG).show() } } override fun onFailure(call: Call<User>, t: Throwable) { Toast.makeText(App.getAppContext(), TAG, Toast.LENGTH_LONG).show() } }) } } "class" -> { val value = sharedPreferences.getString(key, "") Log.d(TAG, "$key has changed and is now $value") val user = Utils.user if (user != null) { if (value != null) { if (value.isBlank()) { MyFirebaseMessagingService.subscribeToTopic("posts-unknown-class") MyFirebaseMessagingService.subscribeToTopic("events-unknown-class") // unsubscribing from old topics if (!user.promotion.isBlank()) { MyFirebaseMessagingService.subscribeToTopic("posts-${user.promotion}", false) MyFirebaseMessagingService.subscribeToTopic("events-${user.promotion}", false) } } else { MyFirebaseMessagingService.subscribeToTopic("posts-$value") MyFirebaseMessagingService.subscribeToTopic("events-$value") // unsubscribing from old topics if (!user.promotion.isBlank()) { MyFirebaseMessagingService.subscribeToTopic("posts-${user.promotion}", false) MyFirebaseMessagingService.subscribeToTopic("events-${user.promotion}", false) } else { MyFirebaseMessagingService.subscribeToTopic("posts-unknown-class", false) MyFirebaseMessagingService.subscribeToTopic("events-unknown-class", false) } } } val updatedUser = User( user.id, sharedPreferences.getString("name", "") ?: "", user.username, sharedPreferences.getString("description", "") ?: "", sharedPreferences.getString("email", "") ?: "", user.isEmailPublic, sharedPreferences.getString("class", "") ?: "", sharedPreferences.getString("gender", "") ?: "", user.events, user.postsLiked) val call = ServiceGenerator.client.updateUser(user.id, updatedUser) call.enqueue(object : Callback<User> { override fun onResponse(call: Call<User>, response: Response<User>) { val user = response.body() if (response.isSuccessful && user != null) { val userPreferences = App.getAppContext().getSharedPreferences("User", Context.MODE_PRIVATE) userPreferences.edit().putString("user", Gson().toJson(user)).apply() } else { Toast.makeText(App.getAppContext(), TAG, Toast.LENGTH_LONG).show() } } override fun onFailure(call: Call<User>, t: Throwable) { Toast.makeText(App.getAppContext(), TAG, Toast.LENGTH_LONG).show() } }) } } "notifications_posts" -> { val enabled = sharedPreferences.getBoolean(key, true) Log.d(TAG, "$key has changed and is now $enabled") MyFirebaseMessagingService.subscribeToTopic("posts-android", enabled) } "notifications_events" -> { val enabled = sharedPreferences.getBoolean(key, true) Log.d(TAG, "$key has changed and is now $enabled") MyFirebaseMessagingService.subscribeToTopic("events-android", enabled) } else -> { } } } override fun onResume() { super.onResume() preferenceScreen.sharedPreferences.registerOnSharedPreferenceChangeListener(this) val barcode = preferenceScreen.sharedPreferences.getString("barcode", "") barcode?.let { findPreference<Preference>("barcode_fragment")?.summary = barcode } } override fun onPause() { super.onPause() preferenceScreen.sharedPreferences.unregisterOnSharedPreferenceChangeListener(this) } companion object { const val TAG = "SETTINGS_FRAGMENT" } }
mit
e95f0a5d4e24524f90953dbdf6649189
44.170984
124
0.5351
6.00827
false
false
false
false
LanternPowered/LanternServer
src/main/kotlin/org/lanternpowered/server/world/LanternLocation.kt
1
15908
/* * Lantern * * Copyright (c) LanternPowered <https://www.lanternpowered.org> * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * This work is licensed under the terms of the MIT License (MIT). For * a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>. */ package org.lanternpowered.server.world import org.lanternpowered.api.key.NamespacedKey import org.lanternpowered.api.util.collections.toImmutableSet import org.lanternpowered.api.util.math.minus import org.lanternpowered.api.util.math.plus import org.lanternpowered.api.util.optional.asOptional import org.lanternpowered.api.util.uncheckedCast import org.lanternpowered.api.world.Location import org.lanternpowered.api.world.World import org.lanternpowered.server.block.LanternLocatableBlock import org.spongepowered.api.block.BlockSnapshot import org.spongepowered.api.block.BlockState import org.spongepowered.api.block.BlockType import org.spongepowered.api.block.entity.BlockEntity import org.spongepowered.api.data.DataTransactionResult import org.spongepowered.api.data.Key import org.spongepowered.api.data.value.CollectionValue import org.spongepowered.api.data.value.MapValue import org.spongepowered.api.data.value.MergeFunction import org.spongepowered.api.data.value.Value import org.spongepowered.api.data.value.ValueContainer import org.spongepowered.api.entity.Entity import org.spongepowered.api.entity.EntityType import org.spongepowered.api.fluid.FluidState import org.spongepowered.api.fluid.FluidType import org.spongepowered.api.scheduler.ScheduledUpdate import org.spongepowered.api.scheduler.TaskPriority import org.spongepowered.api.util.Direction import org.spongepowered.api.world.BlockChangeFlag import org.spongepowered.api.world.LocatableBlock import org.spongepowered.api.world.ServerLocation import org.spongepowered.api.world.biome.BiomeType import org.spongepowered.math.vector.Vector3d import org.spongepowered.math.vector.Vector3i import java.time.Duration import java.time.temporal.TemporalUnit import java.util.Objects import java.util.Optional import java.util.function.BiFunction fun Vector3i.toBiomePosition(): Vector3i = this.div(4).mul(4) // TODO: Move these fun Vector3i.toChunkPosition(): Vector3i = this.div(16) class LanternLocation : Location { object Factory : ServerLocation.Factory { override fun create(world: World, position: Vector3d): Location = LanternLocation(world, position) override fun create(world: World, blockPosition: Vector3i): Location = LanternLocation(world, blockPosition) override fun create(key: NamespacedKey, position: Vector3d): Location = LanternLocation(WeakWorldReference(key), position) override fun create(key: NamespacedKey, blockPosition: Vector3i): Location = LanternLocation(WeakWorldReference(key), blockPosition) } private val worldRef: WeakWorldReference private var lazyPosition: Vector3d? = null private var lazyBlockPosition: Vector3i? = null private var lazyBiomePosition: Vector3i? = null private var lazyChunkPosition: Vector3i? = null private var hashCode = 0 constructor(worldKey: NamespacedKey, position: Vector3d) : this(WeakWorldReference(worldKey), position) constructor(worldKey: NamespacedKey, position: Vector3i) : this(WeakWorldReference(worldKey), position) constructor(world: World, position: Vector3d) : this(WeakWorldReference(world), position) constructor(world: World, position: Vector3i) : this(WeakWorldReference(world), position) constructor(world: WeakWorldReference, position: Vector3d) { this.worldRef = world this.lazyPosition = position } constructor(world: WeakWorldReference, position: Vector3i) { this.worldRef = world this.lazyBlockPosition = position } override fun getWorld(): World = this.worldRef.world ?: error("The world is unavailable.") override fun getWorldKey(): NamespacedKey = this.worldRef.key override fun getWorldIfAvailable(): Optional<World> = this.worldRef.world.asOptional() override fun inWorld(world: World): Boolean = this.world == world override fun asLocatableBlock(): LocatableBlock = LanternLocatableBlock(this, this.block) override fun withWorld(world: World): Location = if (this.worldRef.world == world) this else { val worldRef = WeakWorldReference(world) val blockPosition = this.lazyBlockPosition if (blockPosition != null) { LanternLocation(worldRef, blockPosition) } else { LanternLocation(worldRef, this.position) } } override fun isValid(): Boolean = true // TODO: Check world bounds override fun getX(): Double = this.position.x override fun getY(): Double = this.position.y override fun getZ(): Double = this.position.z override fun getBlockX(): Int = this.blockPosition.x override fun getBlockY(): Int = this.blockPosition.y override fun getBlockZ(): Int = this.blockPosition.z override fun isAvailable(): Boolean = this.worldRef.world != null override fun getPosition(): Vector3d = this.lazyPosition ?: this.lazyBlockPosition!!.toDouble().also { this.lazyPosition = it } override fun getBlockPosition(): Vector3i = this.lazyBlockPosition ?: this.lazyPosition!!.toInt().also { this.lazyBlockPosition = it } override fun getBiomePosition(): Vector3i = this.lazyBiomePosition ?: this.blockPosition.toBiomePosition().also { this.lazyBiomePosition = it } override fun getChunkPosition(): Vector3i = this.lazyChunkPosition ?: this.blockPosition.toChunkPosition().also { this.lazyChunkPosition = it } override fun withPosition(position: Vector3d): Location = if (position == this.lazyPosition) this else LanternLocation(this.worldRef, position) override fun withBlockPosition(position: Vector3i): Location = if (position == this.lazyBlockPosition) this else LanternLocation(this.worldRef, position) override fun asHighestLocation(): Location = this.withBlockPosition(this.world.getHighestPositionAt(this.blockPosition)) override fun add(v: Vector3d): Location = LanternLocation(this.worldRef, this.position + v) override fun add(v: Vector3i): Location = LanternLocation(this.worldRef, this.position + v) override fun add(x: Double, y: Double, z: Double): Location = LanternLocation(this.worldRef, this.position.add(x, y, z)) override fun sub(v: Vector3d): Location = LanternLocation(this.worldRef, this.position - v) override fun sub(v: Vector3i): Location = LanternLocation(this.worldRef, this.position - v) override fun sub(x: Double, y: Double, z: Double): Location = LanternLocation(this.worldRef, this.position.sub(x, y, z)) override fun relativeToBlock(direction: Direction): Location { check(!direction.isSecondaryOrdinal) { "Secondary cardinal directions can't be used here" } return LanternLocation(this.worldRef, this.blockPosition + direction.asBlockOffset()) } override fun relativeTo(direction: Direction): Location = this.add(direction.asOffset()) override fun createEntity(type: EntityType<*>): Entity = this.world.createEntity(type, this.position) override fun spawnEntity(entity: Entity): Boolean { entity.position = this.position return this.world.spawnEntity(entity) } override fun spawnEntities(entities: Iterable<Entity>): Collection<Entity> = entities.asSequence().filter(this::spawnEntity).toImmutableSet() override fun getBlock(): BlockState = this.world.getBlock(this.blockPosition) override fun setBlockType(type: BlockType): Boolean = this.world.setBlock(this.blockPosition, type.defaultState) override fun setBlockType(type: BlockType, flag: BlockChangeFlag): Boolean = this.world.setBlock(this.blockPosition, type.defaultState, flag) override fun setBlock(state: BlockState): Boolean = this.world.setBlock(this.blockPosition, state) override fun setBlock(state: BlockState, flag: BlockChangeFlag): Boolean = this.world.setBlock(this.blockPosition, state, flag) override fun removeBlock(): Boolean = this.world.removeBlock(this.blockPosition) override fun hasBlock(): Boolean = this.world.hasBlockState(this.blockPosition) override fun hasBlockEntity(): Boolean = this.world.getBlockEntity(this.blockPosition).isPresent override fun getBlockEntity(): Optional<BlockEntity> = this.world.getBlockEntity(this.blockPosition).uncheckedCast() override fun getFluid(): FluidState = this.world.getFluid(this.blockPosition) override fun getBiome(): BiomeType = this.world.getBiome(this.blockPosition) override fun getScheduledBlockUpdates(): Collection<ScheduledUpdate<BlockType>> = this.world.scheduledBlockUpdates.getScheduledAt(this.blockPosition) override fun scheduleBlockUpdate(delay: Int, temporalUnit: TemporalUnit): ScheduledUpdate<BlockType> = this.world.scheduledBlockUpdates.schedule(this.blockPosition, this.block.type, delay, temporalUnit) override fun scheduleBlockUpdate(delay: Int, temporalUnit: TemporalUnit, priority: TaskPriority): ScheduledUpdate<BlockType> = this.world.scheduledBlockUpdates.schedule(this.blockPosition, this.block.type, delay, temporalUnit, priority) override fun scheduleBlockUpdate(delay: Duration): ScheduledUpdate<BlockType> = this.world.scheduledBlockUpdates.schedule(this.blockPosition, this.block.type, delay) override fun scheduleBlockUpdate(delay: Duration, priority: TaskPriority): ScheduledUpdate<BlockType> = this.world.scheduledBlockUpdates.schedule(this.blockPosition, this.block.type, delay, priority) override fun getScheduledFluidUpdates(): Collection<ScheduledUpdate<FluidType>> = this.world.scheduledFluidUpdates.getScheduledAt(this.blockPosition) override fun scheduleFluidUpdate(delay: Int, temporalUnit: TemporalUnit): ScheduledUpdate<FluidType> = this.world.scheduledFluidUpdates.schedule(this.blockPosition, this.fluid.type, delay, temporalUnit) override fun scheduleFluidUpdate(delay: Int, temporalUnit: TemporalUnit, priority: TaskPriority): ScheduledUpdate<FluidType> = this.world.scheduledFluidUpdates.schedule(this.blockPosition, this.fluid.type, delay, temporalUnit, priority) override fun scheduleFluidUpdate(delay: Duration): ScheduledUpdate<FluidType> = this.world.scheduledFluidUpdates.schedule(this.blockPosition, this.fluid.type, delay) override fun scheduleFluidUpdate(delay: Duration, priority: TaskPriority): ScheduledUpdate<FluidType> = this.world.scheduledFluidUpdates.schedule(this.blockPosition, this.fluid.type, delay, priority) override fun <T : Any> map(mapper: BiFunction<World, Vector3d, T>): T = mapper.apply(this.world, this.position) override fun <T : Any> mapChunk(mapper: BiFunction<World, Vector3i, T>): T = mapper.apply(this.world, this.chunkPosition) override fun <T : Any> mapBlock(mapper: BiFunction<World, Vector3i, T>): T = mapper.apply(this.world, this.blockPosition) override fun <T : Any> mapBiome(mapper: BiFunction<World, Vector3i, T>): T = mapper.apply(this.world, this.biomePosition) override fun <E : Any> offerSingle(key: Key<out CollectionValue<E, *>>, element: E): DataTransactionResult { TODO("Not yet implemented") } override fun <K : Any, V : Any> offerSingle(key: Key<out MapValue<K, V>>, valueKey: K, value: V): DataTransactionResult { TODO("Not yet implemented") } override fun <E : Any> tryOffer(key: Key<out Value<E>>, value: E): DataTransactionResult { val result = this.world.offer(this.blockPosition, key, value) if (!result.isSuccessful) { throw IllegalArgumentException("Failed offer transaction!") } return result } override fun <E : Any> removeSingle(key: Key<out CollectionValue<E, *>>, element: E): DataTransactionResult { TODO("Not yet implemented") } override fun <E : Any> offer(key: Key<out Value<E>>, value: E): DataTransactionResult = this.world.offer(this.blockPosition, key, value) override fun offer(value: Value<*>): DataTransactionResult = this.world.offer(this.blockPosition, value) override fun <K : Any, V : Any> offerAll(key: Key<out MapValue<K, V>>, map: Map<out K, V>): DataTransactionResult { TODO("Not yet implemented") } override fun offerAll(value: MapValue<*, *>): DataTransactionResult { TODO("Not yet implemented") } override fun offerAll(value: CollectionValue<*, *>): DataTransactionResult { TODO("Not yet implemented") } override fun <E : Any> offerAll(key: Key<out CollectionValue<E, *>>, elements: Collection<E>): DataTransactionResult { TODO("Not yet implemented") } override fun supports(key: Key<*>): Boolean = this.world.supports(this.blockPosition, key) override fun undo(result: DataTransactionResult): DataTransactionResult = this.world.undo(this.blockPosition, result) override fun removeAll(value: CollectionValue<*, *>): DataTransactionResult { TODO("Not yet implemented") } override fun <E : Any> removeAll(key: Key<out CollectionValue<E, *>>, elements: Collection<E>): DataTransactionResult { TODO("Not yet implemented") } override fun removeAll(value: MapValue<*, *>): DataTransactionResult { TODO("Not yet implemented") } override fun <K : Any, V : Any> removeAll(key: Key<out MapValue<K, V>>, map: Map<out K, V>): DataTransactionResult { TODO("Not yet implemented") } override fun <E : Any, V : Value<E>> getValue(key: Key<V>): Optional<V> = this.world.getValue(this.blockPosition, key) override fun getKeys(): Set<Key<*>> = this.world.getKeys(this.blockPosition) override fun getValues(): Set<Value.Immutable<*>> = this.world.getValues(this.blockPosition) override fun remove(key: Key<*>): DataTransactionResult = this.world.remove(this.blockPosition, key) override fun <K : Any> removeKey(key: Key<out MapValue<K, *>>, mapKey: K): DataTransactionResult { TODO("Not yet implemented") } override fun <E : Any> get(key: Key<out Value<E>>): Optional<E> = this.world.get(this.blockPosition, key) override fun <E : Any> get(direction: Direction, key: Key<out Value<E>>): Optional<E> { TODO("Not yet implemented") } override fun copyFrom(that: ValueContainer, function: MergeFunction): DataTransactionResult = this.world.copyFrom(this.blockPosition, that, function) override fun createSnapshot(): BlockSnapshot = this.world.createSnapshot(this.blockPosition) override fun restoreSnapshot(snapshot: BlockSnapshot, force: Boolean, flag: BlockChangeFlag): Boolean = this.world.restoreSnapshot(snapshot.withLocation(this), force, flag) override fun equals(other: Any?): Boolean { return other is LanternLocation && other.worldRef == this.worldRef && other.position == this.position } override fun hashCode(): Int { var hashCode = this.hashCode if (hashCode == 0) { hashCode = Objects.hash(this.worldRef, this.position).also { this.hashCode = it } } return hashCode } }
mit
013ba24cc8d9e9db21ebceab7fc7885d
42.944751
130
0.710334
4.316961
false
false
false
false
LanternPowered/LanternServer
src/main/kotlin/org/lanternpowered/server/data/LanternBoundedElementKeyRegistration.kt
1
4944
/* * Lantern * * Copyright (c) LanternPowered <https://www.lanternpowered.org> * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * This work is licensed under the terms of the MIT License (MIT). For * a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>. */ package org.lanternpowered.server.data import org.lanternpowered.api.util.optional.orNull import org.lanternpowered.api.value.immutableValueOf import org.lanternpowered.server.data.key.ValueKey import org.lanternpowered.server.data.value.CopyHelper import org.lanternpowered.server.util.function.TriConsumer import org.spongepowered.api.data.DataHolder import org.spongepowered.api.data.Key import org.spongepowered.api.data.value.Value @Suppress("UNCHECKED_CAST") internal class LanternBoundedElementKeyRegistration<V : Value<E>, E : Any, H : DataHolder>(key: Key<V>) : LanternElementKeyRegistration<V, E, H>(key), BoundedElementKeyRegistration<V, E, H> { private var minimum: (H.() -> E?)? = null private var maximum: (H.() -> E?)? = null private var coerceInBounds = false override fun coerceInBounds(): BoundedElementKeyRegistration<V, E, H> = apply { this.coerceInBounds = true } override fun <V : Value<E>, E : Comparable<E>, H : DataHolder> BoundedElementKeyRegistration<V, E, H> .range(range: ClosedRange<E>) = apply { this as LanternBoundedElementKeyRegistration<V, E, H> minimum(range.start) maximum(range.endInclusive) } override fun minimum(minimum: E) = apply { // If a copy will exactly be the same, eliminate // the redundant copy call if (CopyHelper.copy(minimum) === minimum) { minimum { minimum } } else { minimum { CopyHelper.copy(minimum) } } } override fun minimum(minimum: H.() -> E) = apply { this.minimum = minimum } override fun minimum(minimum: Key<out Value<E>>) = apply { this.minimum = { get(minimum).orNull() } } override fun maximum(maximum: E) = apply { // If a copy will exactly be the same, eliminate // the redundant copy call if (CopyHelper.copy(maximum) === maximum) { maximum { maximum } } else { maximum { CopyHelper.copy(maximum) } } } override fun maximum(maximum: H.() -> E) = apply { this.maximum = maximum } override fun maximum(maximum: Key<out Value<E>>) = apply { this.maximum = { get(maximum).orNull() } } override fun transform(holder: H, element: E): E { if (!this.coerceInBounds) return super.transform(holder, element) val key = this.key as ValueKey<V, E> val comparator = key.elementComparator val minimum = this.minimum?.invoke(holder) if (minimum != null && comparator.compare(element, minimum) < 0) return minimum val maximum = this.maximum?.invoke(holder) if (maximum != null && comparator.compare(element, maximum) > 0) return maximum return super.transform(holder, element) } override fun validate(holder: H, element: E): Boolean { if (this.coerceInBounds) return super.validate(holder, element) val key = this.key as ValueKey<V, E> val comparator = key.elementComparator val minimum = this.minimum?.invoke(holder) if (minimum != null && comparator.compare(element, minimum) < 0) return false val maximum = this.maximum?.invoke(holder) if (maximum != null && comparator.compare(element, maximum) > 0) return false return super.validate(holder, element) } override fun immutableValueOf(holder: H, element: E): Value.Immutable<E> = immutableValueOf(this.key, element) override fun validator(validator: H.(element: E) -> Boolean) = apply { super.validator(validator) } override fun set(element: E) = apply { super.set(element) } override fun nonRemovable() = apply { super.nonRemovable() } override fun removable() = apply { super.removable() } override fun remove() = apply { super.remove() } override fun addChangeListener(listener: H.(newValue: E?, oldValue: E?) -> Unit) = apply { super.addChangeListener(listener) } override fun addChangeListener(listener: H.(newValue: E?) -> Unit) = apply { super.addChangeListener(listener) } override fun addChangeListener(listener: H.() -> Unit) = apply { super.addChangeListener(listener) } override fun addChangeListener(listener: TriConsumer<H, E?, E?>) = apply { super.addChangeListener(listener) } override fun copy(): LanternLocalKeyRegistration<V, E, H> { val copy = LanternBoundedElementKeyRegistration<V, E, H>(this.key) copyTo(copy) copy.minimum = this.minimum copy.maximum = this.maximum return copy } }
mit
34bd7bb01bdcf49f4d537c28e294fd32
36.740458
130
0.652104
4.144174
false
false
false
false
pie-flavor/Pieconomy
src/main/kotlin/flavor/pie/pieconomy/PieconomyServerAccount.kt
1
5322
package flavor.pie.pieconomy import com.google.common.collect.ImmutableMap import flavor.pie.kludge.* import org.spongepowered.api.event.cause.Cause import org.spongepowered.api.service.context.Context import org.spongepowered.api.service.economy.Currency import org.spongepowered.api.service.economy.EconomyService import org.spongepowered.api.service.economy.account.Account import org.spongepowered.api.service.economy.account.VirtualAccount import org.spongepowered.api.service.economy.transaction.ResultType import org.spongepowered.api.service.economy.transaction.TransactionResult import org.spongepowered.api.service.economy.transaction.TransactionTypes import org.spongepowered.api.service.economy.transaction.TransferResult import org.spongepowered.api.text.Text import java.math.BigDecimal class PieconomyServerAccount(val name: String, val currencies: List<Currency>, val negativeValues: List<Currency>) : PieconomyAccount, VirtualAccount { val money: MutableMap<Currency, BigDecimal> = HashMap() val svc: EconomyService by UncheckedService override fun hasBalance(currency: Currency, contexts: Set<Context>): Boolean = currency in money override fun resetBalances(cause: Cause, contexts: Set<Context>, fireEvent: Boolean): Map<Currency, TransactionResult> = money.keys.map { it to resetBalance(it, cause, contexts, fireEvent) }.toMap() override fun getBalance(currency: Currency, contexts: Set<Context>): BigDecimal = money[currency] ?: BigDecimal.ZERO override fun getBalances(contexts: Set<Context>): Map<Currency, BigDecimal> = ImmutableMap.copyOf(money) override fun getDisplayName(): Text = !name override fun transfer(to: Account, currency: Currency, amount: BigDecimal, cause: Cause, contexts: Set<Context>, fireEvent: Boolean): TransferResult { val res1 = withdraw(currency, amount, cause, contexts, false) if (res1.result != ResultType.SUCCESS) { return PieconomyTransferResult(this, amount, contexts, currency, res1.result, to, true).also { if (fireEvent) post(it, cause) } } val res2 = (to as? PieconomyAccount)?.deposit(currency, amount, cause, contexts, false) ?: to.deposit(currency, amount, cause, contexts) if (res2.result != ResultType.SUCCESS) { deposit(currency, amount, cause, contexts, false) return PieconomyTransferResult(this, amount, contexts, currency, res2.result, to, false).also { if (fireEvent) post(it, cause) } } return PieconomyTransferResult(this, amount, contexts, currency, ResultType.SUCCESS, to, false) } override fun getDefaultBalance(currency: Currency): BigDecimal = BigDecimal.ZERO override fun resetBalance(currency: Currency, cause: Cause, contexts: Set<Context>, fireEvent: Boolean): TransactionResult { money[currency] = BigDecimal.ZERO return PieconomyTransactionResult(this, BigDecimal.ZERO, contexts, currency, ResultType.SUCCESS, TransactionTypes.WITHDRAW).also { if (fireEvent) post(it, cause) } } override fun deposit(currency: Currency, amount: BigDecimal, cause: Cause, contexts: Set<Context>, fireEvent: Boolean): TransactionResult { if (currency !in currencies) { return PieconomyTransactionResult(this, amount, contexts, currency, ResultType.ACCOUNT_NO_SPACE, TransactionTypes.DEPOSIT).also { if (fireEvent) post(it, cause) } } money[currency] = (money[currency] ?: BigDecimal.ZERO) + amount return PieconomyTransactionResult(this, amount, contexts, currency, ResultType.SUCCESS, TransactionTypes.DEPOSIT).also { if (fireEvent) post(it, cause) } } override fun withdraw(currency: Currency, amount: BigDecimal, cause: Cause, contexts: Set<Context>, fireEvent: Boolean): TransactionResult { if (currency !in money) { return PieconomyTransactionResult(this, amount, contexts, currency, ResultType.ACCOUNT_NO_FUNDS, TransactionTypes.WITHDRAW).also { if (fireEvent) post(it, cause) } } val bal = money[currency]!! if (bal < amount && currency !in negativeValues) { return PieconomyTransactionResult(this, amount, contexts, currency, ResultType.ACCOUNT_NO_FUNDS, TransactionTypes.WITHDRAW).also { if (fireEvent) post(it, cause) } } money[currency] = bal - amount return PieconomyTransactionResult(this, amount, contexts, currency, ResultType.SUCCESS, TransactionTypes.WITHDRAW).also { if (fireEvent) post(it, cause) } } override fun getActiveContexts(): Set<Context> = setOf() override fun setBalance(currency: Currency, amount: BigDecimal, cause: Cause, contexts: Set<Context>, fireEvent: Boolean): TransactionResult { if (currency !in currencies) { return PieconomyTransactionResult(this, amount, contexts, currency, ResultType.ACCOUNT_NO_SPACE, TransactionTypes.WITHDRAW).also { if (fireEvent) post(it, cause) } } money[currency] = amount return PieconomyTransactionResult(this, amount, contexts, currency, ResultType.SUCCESS, TransactionTypes.WITHDRAW).also { if (fireEvent) post(it, cause) } } override fun getIdentifier(): String = name fun post(result: TransactionResult, cause: Cause) { EventManager.post(PieconomyTransactionEvent(cause, result)) } }
mit
03cf4850da00945a840df52a8a0fe79a
59.477273
175
0.736189
4.305825
false
false
false
false
cfig/Android_boot_image_editor
bbootimg/src/test/kotlin/EnvironmentVerifierTest.kt
1
1156
// Copyright 2021 [email protected] // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import cfig.utils.EnvironmentVerifier import org.junit.Test class EnvironmentVerifierTest { private val envv = EnvironmentVerifier() @Test fun getHasLz4() { val hasLz4 = envv.hasLz4 println("hasLz4 = $hasLz4") } @Test fun getHasDtc() { val hasDtc = envv.hasDtc println("hasDtc = $hasDtc") } @Test fun getHasXz() { val hasXz = envv.hasXz println("hasXz = $hasXz") } @Test fun getGzip() { val h = envv.hasGzip println("hasGzip = $h") } }
apache-2.0
79448db8b90c0bc8bdd3e09909308674
24.688889
75
0.657439
3.866221
false
true
false
false
Finnerale/FileBase
src/main/kotlin/de/leopoldluley/filebase/Sql.kt
1
2896
package de.leopoldluley.filebase import de.leopoldluley.filebase.models.FileType object Sql { fun createEntriesTable() = """ CREATE TABLE IF NOT EXISTS Entries ( id INTEGER PRIMARY KEY AUTOINCREMENT , name TEXT NOT NULL , tags TEXT , file TEXT NOT NULL , type TEXT NOT NULL , note TEXT ); """ fun createTagsTable() = """ CREATE TABLE IF NOT EXISTS Tags ( name CHAR(40) PRIMARY KEY ON CONFLICT IGNORE ); """ fun queryEntries() = """ SELECT * FROM Entries; """ fun queryEntry(id: Int) = """ SELECT * FROM Entries WHERE id IS $id """ fun queryEntries(name: String, tags: List<String>, type: FileType, onlyComplete: Boolean): String { var q = "SELECT * FROM Entries" if (name.isNotBlank() || tags.isNotEmpty() || type != FileType.NONE) { q += " WHERE " } if (name.isNotBlank()) { q += " name LIKE '%$name%' " } if (type != FileType.NONE) { if (name.isNotBlank()) { q += " AND " } q += " type IS '${type.stringify()}'" } if (tags.isNotEmpty()) { if (name.isNotBlank() || type != FileType.NONE) { q += " AND " } tags.forEachIndexed { index, tag -> if (index > 0) { q += " AND " } println("tag: <$tag>") if (onlyComplete) { q += " tags LIKE '% $tag %' " } else { q += " tags LIKE '%$tag%' " } } } return q } fun insertEntry(name: String, tags: String, file: String, type: FileType, note: String) = """ INSERT INTO Entries (name, tags, file, type, note) VALUES ('$name', '$tags', '$file', '${type.stringify()}', '$note') """ fun updateEntry(id: Int, name: String, tags: String, file: String, type: FileType, note: String) = """ UPDATE Entries SET name = '$name', tags = '$tags', file = '$file', type = '${type.stringify()}', note = '$note' WHERE id IS $id """ fun deleteEntry(id: Int) = """ DELETE FROM Entries WHERE id IS $id """ fun queryAllTags() = """ SELECT * FROM Tags """ fun insertTag(name: String) = """ INSERT INTO Tags (name) VALUES ('$name') """ fun deleteTag(name: String) = """ DELETE FROM Tags WHERE name IS '$name' """ fun updateTag(old: String, new: String) = """ UPDATE Tags SET name = '$new' WHERE name IS '$old' """ }
mit
c80cbff62a3130da140a82df60343948
26.855769
106
0.447169
4.441718
false
false
false
false
kkirstein/proglang-playground
Kotlin/Benchmark/src/main/kotlin/benchmark/mandelbrot.kt
1
1082
/* mandelbrot.kt * Calculate Mandelbrot sets in the Kotlin * (http://kotlinlang.org) programming language */ package benchmark.mandelbrot import complex.Complex // first we need an container for the image data data class Image<T>(val width: Int, val height: Int, val channels: Int, val data: Array<T>) // calculates pixel values fun pixelVal(z0: Complex, nIter: Int = 255, zMax: Double = 2.0): Int { var iter = 0 var z = Complex.zero while(iter <= nIter) { if (z.abs() > zMax) return iter z = z *z + z0 iter++ } return nIter } // generates Mandelbrot set for given coordinates fun mandelbrot(width: Int, height: Int, xCenter: Double, yCenter: Double, pixSize: Double = 4.0 / width): Image<Int> { val imgData = Array(width * height * 3, {_ -> 0}) return Image(width, height, 3, imgData) } // prints an ASCII Mandelbrot set /*for (i in -40.0..40.0) { for (r in -40.0..40.0) { print(mandelbrot(Complex(r - 25.0, i) / 35.0, 256) ?.let { 'a' + (it % 26) } ?: ' ' ) } println() }*/
mit
39b77583b8e4d48acc094f72957ddcb0
22.521739
71
0.60536
3.030812
false
false
false
false
danrien/projectBlueWater
projectBlueWater/src/test/java/com/lasthopesoftware/bluewater/client/browsing/items/media/files/uri/GivenAFileThatIsAvailableRemotely/AndNotAvailableOnDisk/AndExistingFileUsageIsAllowed/WhenGettingTheUri.kt
2
2428
package com.lasthopesoftware.bluewater.client.browsing.items.media.files.uri.GivenAFileThatIsAvailableRemotely.AndNotAvailableOnDisk.AndExistingFileUsageIsAllowed import android.net.Uri import com.lasthopesoftware.bluewater.client.browsing.items.media.audio.uri.CachedAudioFileUriProvider import com.lasthopesoftware.bluewater.client.browsing.items.media.files.ServiceFile import com.lasthopesoftware.bluewater.client.browsing.items.media.files.uri.BestMatchUriProvider import com.lasthopesoftware.bluewater.client.browsing.items.media.files.uri.RemoteFileUriProvider import com.lasthopesoftware.bluewater.client.browsing.library.repository.Library import com.lasthopesoftware.bluewater.client.stored.library.items.files.system.uri.MediaFileUriProvider import com.lasthopesoftware.bluewater.client.stored.library.items.files.uri.StoredFileUriProvider import com.lasthopesoftware.bluewater.shared.promises.extensions.toFuture import com.namehillsoftware.handoff.promises.Promise import io.mockk.every import io.mockk.mockk import org.assertj.core.api.AssertionsForClassTypes.assertThat import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner @RunWith(RobolectricTestRunner::class) class WhenGettingTheUri { companion object { private val returnedFileUri by lazy { val mockStoredFileUriProvider = mockk<StoredFileUriProvider>() every { mockStoredFileUriProvider.promiseFileUri(any()) } returns Promise.empty() val cachedAudioFileUriProvider = mockk<CachedAudioFileUriProvider>() every { cachedAudioFileUriProvider.promiseFileUri(ServiceFile(3)) } returns Promise.empty() val mockMediaFileUriProvider = mockk<MediaFileUriProvider>() every { mockMediaFileUriProvider.promiseFileUri(any()) } returns Promise.empty() val mockRemoteFileUriProvider = mockk<RemoteFileUriProvider>() every { mockRemoteFileUriProvider.promiseFileUri(ServiceFile(3)) } returns Promise(Uri.parse("http://remote-url/to_a_file.mp3")) val bestMatchUriProvider = BestMatchUriProvider( Library().setIsUsingExistingFiles(true), mockStoredFileUriProvider, cachedAudioFileUriProvider, mockMediaFileUriProvider, mockRemoteFileUriProvider ) bestMatchUriProvider.promiseFileUri(ServiceFile(3)).toFuture().get() } } @Test fun thenTheRemoteFileUriIsReturned() { assertThat(returnedFileUri.toString()) .isEqualTo("http://remote-url/to_a_file.mp3") } }
lgpl-3.0
8bfb8c8be43f80a8d940918892d3479d
43.962963
162
0.829901
4.374775
false
true
false
false
gumil/basamto
app/src/main/kotlin/io/github/gumil/basamto/widget/html/SpoilerTextView.kt
1
31556
/* * The MIT License (MIT) * * Copyright 2018 Miguel Panelo * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package io.github.gumil.basamto.widget.html import android.content.Context import android.graphics.BitmapFactory import android.graphics.Color import android.graphics.Typeface import android.os.Environment import android.support.v7.widget.AppCompatTextView import android.text.Spannable import android.text.SpannableStringBuilder import android.text.Spanned import android.text.TextPaint import android.text.style.BackgroundColorSpan import android.text.style.CharacterStyle import android.text.style.ForegroundColorSpan import android.text.style.ImageSpan import android.text.style.QuoteSpan import android.text.style.StrikethroughSpan import android.text.style.StyleSpan import android.text.style.TypefaceSpan import android.text.style.URLSpan import android.util.AttributeSet import android.util.DisplayMetrics import android.view.WindowManager import android.widget.TextView import io.github.gumil.basamto.R import io.github.gumil.basamto.extensions.getColorRes import io.github.gumil.basamto.widget.html.span.CustomQuoteSpan import org.apache.commons.lang3.StringUtils import java.io.File import java.util.* import java.util.regex.Pattern class SpoilerTextView : AppCompatTextView { private val storedSpoilerSpans = ArrayList<CharacterStyle>() private val storedSpoilerStarts = ArrayList<Int>() private val storedSpoilerEnds = ArrayList<Int>() private var isSpoilerClicked = false constructor(context: Context) : super(context) { setLineSpacing(0f, 1.1f) } constructor(context: Context, attrs: AttributeSet) : super(context, attrs) { setLineSpacing(0f, 1.1f) } constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle) { setLineSpacing(0f, 1.1f) } private fun resetSpoilerClicked() { isSpoilerClicked = false } /** * Set the text from html. Handles formatting spoilers, links etc. * * The text must be valid * html. * * @param baseText html text * @param subreddit the subreddit to theme */ fun setTextHtml(baseText: CharSequence) { val text = wrapAlternateSpoilers(saveEmotesFromDestruction(baseText.toString().trim { it <= ' ' })) var builder = text.fromHtml() as SpannableStringBuilder replaceQuoteSpans(builder) //replace the <blockquote> blue line with something more colorful if (text.contains("<a")) { setEmoteSpans(builder) //for emote enabled subreddits } if (text.contains("[")) { setCodeFont(builder) setSpoilerStyle(builder) } if (text.contains("[[d[")) { setStrikethrough(builder) } if (text.contains("[[h[")) { setHighlight(builder) } builder = removeNewlines(builder) builder.append(" ") super.setText(builder, TextView.BufferType.SPANNABLE) } /** * Replaces the blue line produced by <blockquote>s with something more visible * * @param spannable parsed comment text #fromHtml </blockquote> */ private fun replaceQuoteSpans(spannable: Spannable) { val quoteSpans = spannable.getSpans(0, spannable.length, QuoteSpan::class.java) for (quoteSpan in quoteSpans) { val start = spannable.getSpanStart(quoteSpan) val end = spannable.getSpanEnd(quoteSpan) val flags = spannable.getSpanFlags(quoteSpan) spannable.removeSpan(quoteSpan) val barWidth = 4f val gap = 5f spannable.setSpan(CustomQuoteSpan(Color.TRANSPARENT, //background color context.getColorRes(R.color.line), //bar color barWidth, //bar width gap), //bar + text gap start, end, flags) } } private fun wrapAlternateSpoilers(html: String): String { var html = html val htmlSpoilerMatcher = htmlSpoilerPattern.matcher(html) while (htmlSpoilerMatcher.find()) { val newPiece = htmlSpoilerMatcher.group() val inner = ("<a href=\"/spoiler\">spoiler&lt; [[s[ " + newPiece.substring(newPiece.indexOf(">") + 1, newPiece.indexOf("<", newPiece.indexOf(">"))) + "]s]]</a>") html = html.replace(htmlSpoilerMatcher.group(), inner) } return html } private fun saveEmotesFromDestruction(html: String): String { var html = html //Emotes often have no spoiler caption, and therefore are converted to empty anchors. Html.fromHtml removes anchors with zero length node text. Find zero length anchors that start with "/" and add "." to them. val htmlEmotePattern = Pattern.compile("<a href=\"/.*\"></a>") val htmlEmoteMatcher = htmlEmotePattern.matcher(html) while (htmlEmoteMatcher.find()) { var newPiece = htmlEmoteMatcher.group() //Ignore empty tags marked with sp. if (!htmlEmoteMatcher.group().contains("href=\"/sp\"")) { newPiece = newPiece.replace("></a", ">.</a") html = html.replace(htmlEmoteMatcher.group(), newPiece) } } return html } private fun setEmoteSpans(builder: SpannableStringBuilder) { for (span in builder.getSpans(0, builder.length, URLSpan::class.java)) { /*TODO Link Types if (SettingValues.typeInText) { setLinkTypes(builder, span) }*/ val emoteDir = File(Environment.getExternalStorageDirectory(), "RedditEmotes") val emoteFile = File(emoteDir, span.url.replace("/", "").replace("-.*".toRegex(), "") + ".png") //BPM uses "-" to add dynamics for emotes in browser. Fall back to original here if exists. val startsWithSlash = span.url.startsWith("/") val hasOnlyOneSlash = StringUtils.countMatches(span.url, "/") == 1 if (emoteDir.exists() && startsWithSlash && hasOnlyOneSlash && emoteFile.exists()) { //We've got an emote match val start = builder.getSpanStart(span) val end = builder.getSpanEnd(span) val textCovers = builder.subSequence(start, end) //Make sure bitmap loaded works well with screen density. val options = BitmapFactory.Options() val metrics = DisplayMetrics() (context.getSystemService( Context.WINDOW_SERVICE) as WindowManager).defaultDisplay.getMetrics(metrics) options.inDensity = 240 options.inScreenDensity = metrics.densityDpi options.inScaled = true //Since emotes are not directly attached to included text, add extra character to attach image to. builder.removeSpan(span) if (builder.subSequence(start, end)[0] != '.') { builder.insert(start, "") } val emoteBitmap = BitmapFactory.decodeFile(emoteFile.absolutePath, options) builder.setSpan(ImageSpan(context, emoteBitmap), start, start + 1, Spanned.SPAN_INCLUSIVE_INCLUSIVE) //Check if url span has length. If it does, it's a spoiler/caption if (textCovers.length > 1) { builder.setSpan(URLSpan("/sp"), start + 1, end + 1, Spanned.SPAN_INCLUSIVE_INCLUSIVE) builder.setSpan(StyleSpan(Typeface.ITALIC), start + 1, end + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE) } builder.append("\n") //Newline to fix text wrapping issues } } } /* TODO Link Types private fun setLinkTypes(builder: SpannableStringBuilder, span: URLSpan) { var url = span.url if (url.endsWith("/")) { url = url.substring(0, url.length - 1) } val text = builder.subSequence(builder.getSpanStart(span), builder.getSpanEnd(span)) .toString() if (!text.equals(url, ignoreCase = true)) { val contentType = ContentType.getContentType(url) var bod: String try { bod = " (" + (if (url.contains("/") && url.startsWith("/") && url.split("/".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray().size <= 2) url else context.getString(ContentType.getContentID(contentType, false)) + if (contentType === ContentType.Type.LINK) " " + Uri.parse(url) .host else "") + ")" } catch (e: Exception) { bod = (" (" + context.getString(ContentType.getContentID(contentType, false)) + ")") } val b = SpannableStringBuilder(bod) b.setSpan(StyleSpan(Typeface.BOLD), 0, b.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE) b.setSpan(RelativeSizeSpan(0.8f), 0, b.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE) builder.insert(builder.getSpanEnd(span), b) } }*/ private fun setStrikethrough(builder: SpannableStringBuilder) { val offset = "[[d[".length // == "]d]]".length() var start = -1 var end: Int var i = 0 while (i < builder.length - 3) { if (builder[i] == '[' && builder[i + 1] == '[' && builder[i + 2] == 'd' && builder[i + 3] == '[') { start = i + offset } else if (builder[i] == ']' && builder[i + 1] == 'd' && builder[i + 2] == ']' && builder[i + 3] == ']') { end = i builder.setSpan(StrikethroughSpan(), start, end, Spanned.SPAN_INCLUSIVE_INCLUSIVE) builder.delete(end, end + offset) builder.delete(start - offset, start) i -= offset + (end - start) // length of text } i++ } } private fun setHighlight(builder: SpannableStringBuilder) { val offset = "[[h[".length // == "]h]]".length() var start = -1 var end: Int var i = 0 while (i < builder.length - 4) { if (builder[i] == '[' && builder[i + 1] == '[' && builder[i + 2] == 'h' && builder[i + 3] == '[') { start = i + offset } else if (builder[i] == ']' && builder[i + 1] == 'h' && builder[i + 2] == ']' && builder[i + 3] == ']') { end = i builder.setSpan(BackgroundColorSpan(context.getColorRes(R.color.colorAccent)), start, end, Spanned.SPAN_INCLUSIVE_INCLUSIVE) builder.delete(end, end + offset) builder.delete(start - offset, start) i -= offset + (end - start) // length of text } i++ } } /* TODO default to custom tabs fun onLinkClick(url: String?, xOffset: Int, subreddit: String, span: URLSpan?) { if (url == null) { (parent as View).callOnClick() return } val type = ContentType.getContentType(url) val context = context var activity: Activity? = null if (context is Activity) { activity = context } else if (context is android.support.v7.view.ContextThemeWrapper) { activity = context.baseContext as Activity } else if (context is ContextWrapper) { val context1 = context.baseContext if (context1 is Activity) { activity = context1 } else if (context1 is ContextWrapper) { val context2 = context1.baseContext if (context2 is Activity) { activity = context2 } else if (context2 is ContextWrapper) { activity = (context2 as android.support.v7.view.ContextThemeWrapper).baseContext as Activity } } } else { throw RuntimeException("Could not find activity from context:" + context) } if (!PostMatch.openExternal(url) || type === ContentType.Type.VIDEO) { when (type) { DEVIANTART, IMGUR, XKCD -> if (SettingValues.image) { val intent2 = Intent(activity, MediaView::class.java) intent2.putExtra(MediaView.EXTRA_URL, url) intent2.putExtra(MediaView.SUBREDDIT, subreddit) activity!!.startActivity(intent2) } else { Reddit.defaultShare(url, activity) } REDDIT -> OpenRedditLink(activity, url) LINK -> { LogUtil.v("Opening link") LinkUtil.openUrl(url, Palette.getColor(subreddit), activity) } SELF -> { } STREAMABLE, VID_ME -> openStreamable(url, subreddit) ALBUM -> if (SettingValues.album) { if (SettingValues.albumSwipe) { val i = Intent(activity, AlbumPager::class.java) i.putExtra(Album.EXTRA_URL, url) i.putExtra(AlbumPager.SUBREDDIT, subreddit) activity!!.startActivity(i) } else { val i = Intent(activity, Album::class.java) i.putExtra(Album.SUBREDDIT, subreddit) i.putExtra(Album.EXTRA_URL, url) activity!!.startActivity(i) } } else { Reddit.defaultShare(url, activity) } TUMBLR -> if (SettingValues.image) { if (SettingValues.albumSwipe) { val i = Intent(activity, TumblrPager::class.java) i.putExtra(Album.EXTRA_URL, url) activity!!.startActivity(i) } else { val i = Intent(activity, TumblrPager::class.java) i.putExtra(Album.EXTRA_URL, url) activity!!.startActivity(i) } } else { Reddit.defaultShare(url, activity) } IMAGE -> openImage(url, subreddit) GIF -> openGif(url, subreddit, activity) NONE -> { } VIDEO -> { if (Reddit.videoPlugin) { try { val sharingIntent = Intent(Intent.ACTION_SEND) sharingIntent.setClassName("ccrama.me.slideyoutubeplugin", "ccrama.me.slideyoutubeplugin.YouTubeView") sharingIntent.putExtra("url", url) activity!!.startActivity(sharingIntent) } catch (e: Exception) { Reddit.defaultShare(url, activity) } } else { Reddit.defaultShare(url, activity) } isSpoilerClicked = true setOrRemoveSpoilerSpans(xOffset, span) } SPOILER -> { isSpoilerClicked = true setOrRemoveSpoilerSpans(xOffset, span) } EXTERNAL -> Reddit.defaultShare(url, activity) } } else { Reddit.defaultShare(url, context) } } fun onLinkLongClick(baseUrl: String?, event: MotionEvent) { if (baseUrl == null) { return } val url = StringEscapeUtils.unescapeHtml4(baseUrl) performHapticFeedback(HapticFeedbackConstants.LONG_PRESS) var activity: Activity? = null val context = context if (context is Activity) { activity = context } else if (context is android.support.v7.view.ContextThemeWrapper) { activity = context.baseContext as Activity } else if (context is ContextWrapper) { val context1 = context.baseContext if (context1 is Activity) { activity = context1 } else if (context1 is ContextWrapper) { val context2 = context1.baseContext if (context2 is Activity) { activity = context2 } else if (context2 is ContextWrapper) { activity = (context2 as android.support.v7.view.ContextThemeWrapper).baseContext as Activity } } } else { throw RuntimeException("Could not find activity from context:" + context) } if (activity != null && !activity.isFinishing) { if (SettingValues.peek) { Peek.into(R.layout.peek_view, object : SimpleOnPeek() { fun onInflated(peekView: PeekView, rootView: View) { //do stuff val text = rootView.findViewById(R.id.title) as TextView text.text = url text.setTextColor(Color.WHITE) (rootView.findViewById(R.id.peek) as PeekMediaView).setUrl(url) peekView.addButton(R.id.copy, object : OnButtonUp() { fun onButtonUp() { val clipboard = rootView.context .getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager val clip = ClipData.newPlainText("Link", url) clipboard.primaryClip = clip Toast.makeText(rootView.context, R.string.submission_link_copied, Toast.LENGTH_SHORT).show() } }) peekView.setOnRemoveListener(object : OnRemove() { fun onRemove() { (rootView.findViewById(R.id.peek) as PeekMediaView).doClose() } }) peekView.addButton(R.id.share, object : OnButtonUp() { fun onButtonUp() { Reddit.defaultShareText("", url, rootView.context) } }) peekView.addButton(R.id.pop, object : OnButtonUp() { fun onButtonUp() { Reddit.defaultShareText("", url, rootView.context) } }) peekView.addButton(R.id.external, object : OnButtonUp() { fun onButtonUp() { LinkUtil.openExternally(url, context, false) } }) peekView.setOnPop(object : OnPop() { fun onPop() { onLinkClick(url, 0, "", null) } }) } }) .with(PeekViewOptions().setFullScreenPeek(true)) .show(activity as PeekViewActivity?, event) } else { val b = BottomSheet.Builder(activity).title(url).grid() val attrs = intArrayOf(R.attr.tintColor) val ta = getContext().obtainStyledAttributes(attrs) val color = ta.getColor(0, Color.WHITE) val open = resources.getDrawable(R.drawable.ic_open_in_browser) open.setColorFilter(color, PorterDuff.Mode.SRC_ATOP) val share = resources.getDrawable(R.drawable.ic_share) share.setColorFilter(color, PorterDuff.Mode.SRC_ATOP) val copy = resources.getDrawable(R.drawable.ic_content_copy) copy.setColorFilter(color, PorterDuff.Mode.SRC_ATOP) ta.recycle() b.sheet(R.id.open_link, open, resources.getString(R.string.submission_link_extern)) b.sheet(R.id.share_link, share, resources.getString(R.string.share_link)) b.sheet(R.id.copy_link, copy, resources.getString(R.string.submission_link_copy)) val finalActivity = activity b.listener(DialogInterface.OnClickListener { dialog, which -> when (which) { R.id.open_link -> LinkUtil.openExternally(url, context, false) R.id.share_link -> Reddit.defaultShareText("", url, finalActivity) R.id.copy_link -> { val clipboard = finalActivity.getSystemService( Context.CLIPBOARD_SERVICE) as ClipboardManager val clip = ClipData.newPlainText("Link", url) clipboard.primaryClip = clip Toast.makeText(finalActivity, R.string.submission_link_copied, Toast.LENGTH_SHORT).show() } } }).show() } } } private fun openGif(url: String, subreddit: String, activity: Activity?) { if (SettingValues.gif) { if (GifUtils.AsyncLoadGif.getVideoType(url).shouldLoadPreview()) { LinkUtil.openUrl(url, Palette.getColor(subreddit), activity) } else { val myIntent = Intent(context, MediaView::class.java) myIntent.putExtra(MediaView.EXTRA_URL, url) myIntent.putExtra(MediaView.SUBREDDIT, subreddit) context.startActivity(myIntent) } } else { Reddit.defaultShare(url, context) } } private fun openStreamable(url: String, subreddit: String) { if (SettingValues.video) { //todo maybe streamable here? val myIntent = Intent(context, MediaView::class.java) myIntent.putExtra(MediaView.EXTRA_URL, url) myIntent.putExtra(MediaView.SUBREDDIT, subreddit) context.startActivity(myIntent) } else { Reddit.defaultShare(url, context) } } private fun openImage(submission: String, subreddit: String) { if (SettingValues.image) { val myIntent = Intent(context, MediaView::class.java) myIntent.putExtra(MediaView.EXTRA_URL, submission) myIntent.putExtra(MediaView.SUBREDDIT, subreddit) context.startActivity(myIntent) } else { Reddit.defaultShare(submission, context) } }*/ private fun setOrRemoveSpoilerSpans(endOfLink: Int, span: URLSpan?) { if (span != null) { val offset = if (span.url.contains("hidden")) -1 else 2 val text = text as Spannable // add 2 to end of link since there is a white space between the link text and the spoiler val foregroundColors = text.getSpans(endOfLink + offset, endOfLink + offset, ForegroundColorSpan::class.java) if (foregroundColors.size > 1) { text.removeSpan(foregroundColors[1]) setText(text) } else { for (i in 1 until storedSpoilerStarts.size) { if (storedSpoilerStarts[i] < endOfLink + offset && storedSpoilerEnds[i] > endOfLink + offset) { try { text.setSpan(storedSpoilerSpans[i], storedSpoilerStarts[i], if (storedSpoilerEnds[i] > text.toString().length) storedSpoilerEnds[i] + offset else storedSpoilerEnds[i], Spanned.SPAN_INCLUSIVE_INCLUSIVE) } catch (ignored: Exception) { //catch out of bounds ignored.printStackTrace() } } } setText(text) } } } /** * Set the necessary spans for each spoiler. * * The algorithm works in the same way as * `setCodeFont`. * * @param sequence * @return */ private fun setSpoilerStyle(sequence: SpannableStringBuilder): CharSequence { var start = 0 var end = 0 var i = 0 while (i < sequence.length) { if (sequence[i] == '[' && i < sequence.length - 3) { if (sequence[i + 1] == '[' && sequence[i + 2] == 's' && sequence[i + 3] == '[') { start = i } } else if (sequence[i] == ']' && i < sequence.length - 3) { if (sequence[i + 1] == 's' && sequence[i + 2] == ']' && sequence[i + 3] == ']') { end = i } } if (end > start) { sequence.delete(end, end + 4) sequence.delete(start, start + 4) val color = context.getColorRes(R.color.colorAccent) val backgroundColorSpan = BackgroundColorSpan(color) val foregroundColorSpan = ForegroundColorSpan(color) val underneathColorSpan = ForegroundColorSpan(Color.WHITE) val urlSpan = sequence.getSpans(start, start, URLSpan::class.java)[0] sequence.setSpan(urlSpan, sequence.getSpanStart(urlSpan), start - 1, Spanned.SPAN_INCLUSIVE_INCLUSIVE) sequence.setSpan(URLSpanNoUnderline("#spoilerhidden"), start, end - 4, Spannable.SPAN_INCLUSIVE_INCLUSIVE) // spoiler text has a space at the front sequence.setSpan(backgroundColorSpan, start + 1, end - 4, Spannable.SPAN_INCLUSIVE_INCLUSIVE) sequence.setSpan(underneathColorSpan, start, end - 4, Spannable.SPAN_INCLUSIVE_INCLUSIVE) sequence.setSpan(foregroundColorSpan, start, end - 4, Spannable.SPAN_INCLUSIVE_INCLUSIVE) storedSpoilerSpans.add(underneathColorSpan) storedSpoilerSpans.add(foregroundColorSpan) storedSpoilerSpans.add(backgroundColorSpan) // Shift 1 to account for remove of beginning "<" storedSpoilerStarts.add(start - 1) storedSpoilerStarts.add(start - 1) storedSpoilerStarts.add(start - 1) storedSpoilerEnds.add(end - 5) storedSpoilerEnds.add(end - 5) storedSpoilerEnds.add(end - 5) sequence.delete(start - 2, start - 1) // remove the trailing < start = 0 end = 0 i -= 5 // move back to compensate for removal of [[s[ } i++ } return sequence } private inner class URLSpanNoUnderline(url: String) : URLSpan(url) { override fun updateDrawState(ds: TextPaint) { super.updateDrawState(ds) ds.isUnderlineText = false } } /** * Sets the styling for string with code segments. * * The general process is to search for * `[[<[` and `]>]]` tokens to find the code fragments within the * escaped text. A `Spannable` is created which which breaks up the origin sequence * into non-code and code fragments, and applies a monospace font to the code fragments. * * @param sequence the Spannable generated from Html.fromHtml * @return the message with monospace font applied to code fragments */ private fun setCodeFont(sequence: SpannableStringBuilder): SpannableStringBuilder { var start = 0 var end = 0 var i = 0 while (i < sequence.length) { if (sequence[i] == '[' && i < sequence.length - 3) { if (sequence[i + 1] == '[' && sequence[i + 2] == '<' && sequence[i + 3] == '[') { start = i } } else if (sequence[i] == ']' && i < sequence.length - 3) { if (sequence[i + 1] == '>' && sequence[i + 2] == ']' && sequence[i + 3] == ']') { end = i } } if (end > start) { sequence.delete(end, end + 4) sequence.delete(start, start + 4) sequence.setSpan(TypefaceSpan("monospace"), start, end - 4, Spannable.SPAN_INCLUSIVE_INCLUSIVE) start = 0 end = 0 i = i - 4 // move back to compensate for removal of [[<[ } i++ } return sequence } companion object { private val htmlSpoilerPattern = Pattern.compile("<a href=\"([#/](?:spoiler|sp|s))\">([^<]*)</a>") private fun removeNewlines(s: SpannableStringBuilder): SpannableStringBuilder { var start = 0 var end = s.length while (start < end && Character.isWhitespace(s[start])) { start++ } while (end > start && Character.isWhitespace(s[end - 1])) { end-- } return s.subSequence(start, end) as SpannableStringBuilder } } }
mit
0428094427d6f3096e2168e047e7f59d
40.519737
217
0.524925
4.981844
false
false
false
false
daugeldauge/NeePlayer
app/src/main/java/com/neeplayer/ui/albums/AlbumSongAdapter.kt
1
3962
package com.neeplayer.ui.albums import android.content.Context import android.graphics.drawable.AnimatedVectorDrawable import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.databinding.DataBindingUtil import androidx.recyclerview.widget.RecyclerView import com.neeplayer.R import com.neeplayer.databinding.AlbumBinding import com.neeplayer.databinding.SongBinding import com.neeplayer.model.AlbumWithSongs import com.neeplayer.model.Song class AlbumSongAdapter(private val context: Context, albums: List<AlbumWithSongs>, private val onSongClicked: (Song) -> Unit) : RecyclerView.Adapter<RecyclerView.ViewHolder>() { private val ALBUM_ITEM = 0 private val SONG_ITEM = 1 private sealed class Item { class AlbumItem(val albumWithSongs: AlbumWithSongs) : Item() class SongItem(val song: Song) : Item() } private val items = albums.flatMap { listOf(Item.AlbumItem(it)).plus(it.songs.map { Item.SongItem(it) }) } private var nowPlaying: Song? = null private var paused = false override fun getItemCount(): Int = items.size override fun getItemViewType(position: Int): Int = when (items[position]) { is Item.AlbumItem -> ALBUM_ITEM is Item.SongItem -> SONG_ITEM } class SongViewHolder(view: View) : RecyclerView.ViewHolder(view) { val binding = DataBindingUtil.bind<SongBinding>(view)!! } class AlbumViewHolder(view: View) : RecyclerView.ViewHolder(view) { val binding = DataBindingUtil.bind<AlbumBinding>(view)!! } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder { val inflater = LayoutInflater.from(context) return when (viewType) { ALBUM_ITEM -> AlbumViewHolder(AlbumBinding.inflate(inflater, parent, false).root) SONG_ITEM -> { val binding = SongBinding.inflate(inflater, parent, false) binding.animationNowPlaying.setImageResource(R.drawable.now_playing) SongViewHolder(binding.root) } else -> throw IllegalStateException() } } override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { when (val item = items[position]) { is Item.AlbumItem -> { val binding = (holder as AlbumViewHolder).binding binding.album = item.albumWithSongs.album binding.info = item.albumWithSongs.info } is Item.SongItem -> { val binding = (holder as SongViewHolder).binding val song = item.song binding.song = song binding.root.setOnClickListener { onSongClicked(song) } if (song == nowPlaying) { binding.songTrack.visibility = View.GONE binding.animationNowPlaying.visibility = View.VISIBLE (binding.animationNowPlaying.drawable as AnimatedVectorDrawable).apply { if (paused) { stop() } else { start() } } } else { binding.songTrack.visibility = View.VISIBLE binding.animationNowPlaying.visibility = View.GONE } } } } fun updateNowPlaying(nowPlaying: Song, paused: Boolean) { val previous = this.nowPlaying this.paused = paused this.nowPlaying = nowPlaying notifySongChanged(previous) notifySongChanged(nowPlaying) } private fun notifySongChanged(song: Song?) { items.mapIndexed { i, item -> if (item is Item.SongItem && item.song == song) i else null } .filterNotNull() .forEach { notifyItemChanged(it) } } }
mit
5637c806f23e9015643b55758393c8a0
36.377358
177
0.61686
4.909542
false
false
false
false
natanieljr/droidmate
project/deviceComponents/deviceControlDaemon/src/androidTest/java/org/droidmate/uiautomator2daemon/exploration/ActionExecution.kt
1
18123
package org.droidmate.uiautomator2daemon.exploration import android.app.UiAutomation import android.content.Context import android.content.Intent import android.graphics.Bitmap import android.media.AudioManager import android.net.wifi.WifiManager import android.os.Bundle import android.support.test.uiautomator.* import android.util.Log import android.view.KeyEvent import android.view.accessibility.AccessibilityNodeInfo import kotlinx.coroutines.* import org.droidmate.deviceInterface.DeviceConstants import org.droidmate.deviceInterface.exploration.* import org.droidmate.uiautomator2daemon.uiautomatorExtensions.* import org.droidmate.uiautomator2daemon.uiautomatorExtensions.UiParser.Companion.computeIdHash import org.droidmate.uiautomator2daemon.uiautomatorExtensions.UiSelector.actableAppElem import org.droidmate.uiautomator2daemon.uiautomatorExtensions.UiSelector.isWebView import java.io.FileOutputStream import kotlin.math.max import kotlin.system.measureNanoTime import kotlin.system.measureTimeMillis var idleTimeout: Long = 100 var interactiveTimeout: Long = 1000 var measurePerformance = true @Suppress("ConstantConditionIf") inline fun <T> nullableDebugT(msg: String, block: () -> T?, timer: (Long) -> Unit = {}, inMillis: Boolean = false): T? { var res: T? = null if (measurePerformance) { measureNanoTime { res = block.invoke() }.let { timer(it) Log.d(DeviceConstants.deviceLogcatTagPrefix + "performance","TIME: ${if (inMillis) "${(it / 1000000.0).toInt()} ms" else "${it / 1000.0} ns/1000"} \t $msg") } } else res = block.invoke() return res } inline fun <T> debugT(msg: String, block: () -> T?, timer: (Long) -> Unit = {}, inMillis: Boolean = false): T { return nullableDebugT(msg, block, timer, inMillis) ?: throw RuntimeException("debugT is non nullable use nullableDebugT instead") } private const val logTag = DeviceConstants.deviceLogcatTagPrefix + "ActionExecution" var lastId = 0 var isWithinQueue = false @Suppress("DEPRECATION") suspend fun ExplorationAction.execute(env: UiAutomationEnvironment): Any { val idMatch: (Int) -> SelectorCondition = {idHash ->{ n: AccessibilityNodeInfo, xPath -> val layer = env.lastWindows.find { it.w.windowId == n.windowId }?.layer ?: n.window?.layer layer != null && idHash == computeIdHash(xPath, layer) }} Log.d(logTag, "START execution ${toString()}($id)") val result: Any = when(this) { // REMARK this has to be an assignment for when to check for exhaustiveness is Click -> { env.device.verifyCoordinate(x, y) env.device.click(x, y, interactiveTimeout).apply { delay(delay) } } is Tick -> { var success = UiHierarchy.findAndPerform(env, idMatch(idHash)) { val newStatus = !it.isChecked it.isChecked = newStatus it.isChecked == newStatus } if (!success) { env.device.verifyCoordinate(x, y) success = env.device.click(x, y, interactiveTimeout) } delay(delay) success } is ClickEvent -> { var node: AccessibilityNodeInfo? = null UiHierarchy.findAndPerform(env, idMatch(idHash)) { nodeInfo -> // do this for API Level above 19 (exclusive) node = nodeInfo if (nodeInfo.isFocusable) { nodeInfo.performAction(AccessibilityNodeInfo.ACTION_FOCUS) Log.d(logTag, "focus target element to ensure click event is registered") } nodeInfo.performAction(AccessibilityNodeInfo.ACTION_CLICK) }.also { Log.d(logTag, "perform ClickEvent on $idHash successful=$it") if (it) { delay(delay) } // wait for display update else { val res = env.device.click(x, y, interactiveTimeout).apply { if(this) delay(delay) } Log.d(logTag, "event click failed, fallback to coordinate click; success = $res") } } } is LongClickEvent -> { UiHierarchy.findAndPerform(env, idMatch(idHash)) { nodeInfo -> // do this for API Level above 19 (exclusive) if(nodeInfo.isFocusable){ nodeInfo.performAction(AccessibilityNodeInfo.ACTION_FOCUS) Log.d(logTag, "focus target element to ensure long-click event is registered") } nodeInfo.performAction(AccessibilityNodeInfo.ACTION_LONG_CLICK)}.also { Log.d(logTag, "perform LongClickEvent on $idHash successful=$it") if(it) { delay(delay) } // wait for display update else { val res = env.device.longClick(x, y, interactiveTimeout).apply { if(this) delay(delay) } Log.d(logTag, "event long click failed, fallback to coordinate long click; success = $res") } } } is LongClick -> { env.device.verifyCoordinate(x, y) env.device.longClick(x, y, interactiveTimeout).apply { delay(delay) } } is GlobalAction -> when (actionType) { ActionType.PressBack -> env.device.pressBack() ActionType.PressHome -> env.device.pressHome() ActionType.EnableWifi -> { val wfm = env.context.getSystemService(Context.WIFI_SERVICE) as WifiManager wfm.setWifiEnabled(true).also { if (!it) Log.w(logTag, "Failed to ensure WiFi is enabled!") } } ActionType.MinimizeMaximize -> { env.device.minimizeMaximize() true } ActionType.FetchGUI -> fetchDeviceData(env = env, afterAction = false) ActionType.Terminate -> false /* should never be transferred to the device */ ActionType.PressEnter -> env.device.pressEnter() ActionType.CloseKeyboard -> if (env.isKeyboardOpen()) //(UiHierarchy.any(env.device) { node, _ -> env.keyboardPkgs.contains(node.packageName) }) env.device.pressBack() else true }//.also { if (it is Boolean && it) { delay(idleTimeout) } }// wait for display update (if no Fetch action) is TextInsert -> UiHierarchy.findAndPerform(env, idMatch(idHash)) { nodeInfo -> if(nodeInfo.isFocusable){ nodeInfo.performAction(AccessibilityNodeInfo.ACTION_FOCUS) Log.d(logTag,"focus input-field") }else if(nodeInfo.isClickable){ nodeInfo.performAction(AccessibilityNodeInfo.ACTION_CLICK) Log.d(logTag, "click non-focusable input-field") } // do this for API Level above 19 (exclusive) val args = Bundle() args.putCharSequence(AccessibilityNodeInfo.ACTION_ARGUMENT_SET_TEXT_CHARSEQUENCE, text) nodeInfo.performAction(AccessibilityNodeInfo.ACTION_SET_TEXT, args).also { // if(it) { delay(idleTimeout) } // wait for display update Log.d(logTag, "perform successful=$it") if(sendEnter && !isWithinQueue){ Log.d(logTag, "trigger enter") env.device.pressEnter() } // when doing multiple action sending enter may trigger a continue button but not all elements are yet filled if(nodeInfo.isFocusable){ nodeInfo.performAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS) } // close the keyboard if it is open after the text insert if(closeKeyboard && env.isKeyboardOpen()){ Log.i(logTag, "open keyboard detected after text insert, try to close it") env.device.pressBack() } delay(delay) } } is RotateUI -> env.device.rotate(rotation, env.automation) is LaunchApp -> { env.device.pressKeyCode(KeyEvent.KEYCODE_WAKEUP) env.device.launchApp(packageName, env, launchActivityDelay, timeout) } is Swipe -> env.device.twoPointAction(start,end){ x0, y0, x1, y1 -> env.device.swipe(x0, y0, x1, y1, stepSize) } is TwoPointerGesture -> TODO("this requires a call on UiObject, which we currently do not match to our ui-extraction") is PinchIn -> TODO("this requires a call on UiObject, which we currently do not match to our ui-extraction") is PinchOut -> TODO("this requires a call on UiObject, which we currently do not match to our ui-extraction") is Scroll -> // TODO we may trigger the UiObject2 method instead UiHierarchy.findAndPerform(env, idMatch(idHash)) { nodeInfo -> // do this for API Level above 19 (exclusive) nodeInfo.performAction(AccessibilityNodeInfo.ACTION_SCROLL_FORWARD)}.also { if(it) { delay(idleTimeout) } // wait for display update Log.d(logTag, "perform successful=$it") } is ActionQueue -> { var success = true isWithinQueue = true actions.forEachIndexed { i,action -> if(i==actions.size-1) isWithinQueue = false // reset var at the end of queue success = success && action.execute(env).also{ if(i<actions.size-1 && ((action is TextInsert && actions[i+1] is Click) || action is Swipe)) { if(action is Swipe){ Log.d(logTag, "delay after swipe") delay(delay) } getOrStoreImgPixels(env.captureScreen(), env, action.id) } else if(i < actions.size - 1 && screenshotForEach){ getOrStoreImgPixels(env.captureScreen(), env, action.id) } }.let{ if(it is Boolean) it else true } }.apply{ delay(delay) getOrStoreImgPixels(env.captureScreen(),env) } } else -> throw DeviceDaemonException("not implemented action $name was called in exploration/ActionExecution") } Log.d(logTag, "END execution of ${toString()} ($id)") return result } //REMARK keep the order of first wait for windowUpdate, then wait for idle, then extract windows to minimize synchronization issues with opening/closing keyboard windows private suspend fun waitForSync(env: UiAutomationEnvironment, afterAction: Boolean) { try { env.lastWindows.firstOrNull { it.isApp() && !it.isKeyboard && !it.isLauncher }?.let { env.device.waitForWindowUpdate(it.w.pkgName, env.interactiveTimeout) //wait sync on focused window } debugT("wait for IDLE avg = ${time / max(1, cnt)} ms", { env.automation.waitForIdle(100, env.idleTimeout) // env.device.waitForIdle(env.idleTimeout) // this has a minimal delay of 500ms between events until the device is considered idle }, inMillis = true, timer = { Log.d(logTag, "time=${it / 1000000}") time += it / 1000000 cnt += 1 }) // this sometimes really sucks in performance but we do not yet have any reliable alternative debugOut("check if we have a webView", debugFetch) if (afterAction && UiHierarchy.any(env, cond = isWebView)) { // waitForIdle is insufficient for WebView's therefore we need to handle the stabilize separately debugOut("WebView detected wait for interactive element with different package name", debugFetch) UiHierarchy.waitFor(env, interactiveTimeout, actableAppElem) } } catch(e: java.util.concurrent.TimeoutException) { Log.e(logTag, "No idle state with idle timeout: 100ms within global timeout: ${env.idleTimeout}ms", e) } } /** compressing an image no matter the quality, takes long time therefore the option of storing these asynchronous * and transferring them later is available via configuration */ private fun getOrStoreImgPixels(bm: Bitmap?, env: UiAutomationEnvironment, actionId: Int = lastId): ByteArray = debugT("wait for screen avg = ${wt / max(1, wc)}",{ when{ // if we couldn't capture screenshots bm == null ->{ Log.w(logTag,"create empty image") ByteArray(0) } env.delayedImgTransfer ->{ backgroundScope.launch(Dispatchers.IO){ // we could use an actor getting id and bitmap via channel, instead of starting another coroutine each time debugOut("create screenshot for action $actionId") val os = FileOutputStream(env.imgDir.absolutePath+ "/"+actionId+".jpg") bm.compress(Bitmap.CompressFormat.JPEG, env.imgQuality, os) os.close() bm.recycle() } ByteArray(0) } else -> UiHierarchy.compressScreenshot(bm).also{ bm.recycle() } } }, inMillis = true, timer = { wt += it / 1000000.0; wc += 1 }) private var time: Long = 0 private var cnt = 0 private var wt = 0.0 private var wc = 0 private const val debugFetch = false private val isInteractive = { w: UiElementPropertiesI -> w.clickable || w.longClickable || w.checked!=null || w.isInputField} suspend fun fetchDeviceData(env: UiAutomationEnvironment, afterAction: Boolean = false): DeviceResponse = coroutineScope{ debugOut("start fetch execution",debugFetch) waitForSync(env,afterAction) var windows: List<DisplayedWindow> = env.getDisplayedWindows() var isSuccessful = true // fetch the screenshot if available var img = env.captureScreen() // could maybe use Espresso View.DecorativeView to fetch screenshot instead debugOut("start element extraction",debugFetch) // we want the ui fetch first as it is fast but will likely solve synchronization issues val uiHierarchy = UiHierarchy.fetch(windows,img).let{ if(it == null || (!windows.isHomeScreen() && it.none (isInteractive)) ) { Log.w(logTag, "first ui extraction failed or no interactive elements were found \n $it, \n ---> start a second try") windows = env.getDisplayedWindows() img = env.captureScreen() UiHierarchy.fetch( windows, img ).also{ secondRes -> Log.d(logTag, "second try resulted in ${secondRes?.size} elements") } //retry once for the case that AccessibilityNode tree was not yet stable } else it } ?: emptyList<UiElementPropertiesI>() .also { isSuccessful = false Log.e(logTag, "could not parse current UI screen ( $windows )") throw java.lang.RuntimeException("UI extraction failed for windows: $windows") } // Log.d(logTag, "uiHierarchy = $uiHierarchy") uiHierarchy.also { debugOut("INTERACTIVE Element in UI = ${it.any (isInteractive)}") } // val xmlDump = UiHierarchy.getXml(device) val focusedWindow = windows.filter { it.isExtracted() && !it.isKeyboard }.let { appWindows -> ( appWindows.firstOrNull{ it.w.hasFocus || it.w.hasInputFocus } ?: appWindows.firstOrNull()) } val focusedAppPkg = focusedWindow ?.w?.pkgName ?: "no AppWindow detected" debugOut("determined focused window $focusedAppPkg inputF=${focusedWindow?.w?.hasInputFocus}, focus=${focusedWindow?.w?.hasFocus}") debugOut("started async ui extraction",debugFetch) debugOut("compute img pixels",debugFetch) val imgPixels = getOrStoreImgPixels(img,env) var xml: String = "TODO parse widget list on Pc if we need the XML or introduce a debug property to enable parsing" + ", because (currently) we would have to traverse the tree a second time" if(debugEnabled) xml = UiHierarchy.getXml(env) env.lastResponse = DeviceResponse.create( isSuccessful = isSuccessful, uiHierarchy = uiHierarchy, uiDump = xml, launchedActivity = env.launchedMainActivity, capturedScreen = img != null, screenshot = imgPixels, appWindows = windows.mapNotNull { if(it.isExtracted()) it.w else null }, isHomeScreen = windows.isHomeScreen() ) env.lastResponse } //private val deviceModel: String by lazy { // Log.d(DeviceConstants.uiaDaemon_logcatTag, "getDeviceModel()") // val model = Build.MODEL // val manufacturer = Build.MANUFACTURER // val fullModelName = "$manufacturer-$model/$api" // Log.d(DeviceConstants.uiaDaemon_logcatTag, "Device model: $fullModelName") // fullModelName // } private fun UiDevice.verifyCoordinate(x:Int,y:Int){ assert(x in 0 until displayWidth) { "Error on click coordinate invalid x:$x" } assert(y in 0 until displayHeight) { "Error on click coordinate invalid y:$y" } } private typealias twoPointStepableAction = (x0:Int,y0:Int,x1:Int,y1:Int)->Boolean private fun UiDevice.twoPointAction(start: Pair<Int,Int>, end: Pair<Int,Int>, action: twoPointStepableAction):Boolean{ val (x0,y0) = start val (x1,y1) = end verifyCoordinate(x0,y0) verifyCoordinate(x1,y1) return action(x0, y0, x1, y1) } private suspend fun UiDevice.minimizeMaximize(){ val currentPackage = currentPackageName Log.d(logTag, "Original package name $currentPackage") pressRecentApps() // Cannot use wait for changes because it crashes UIAutomator delay(100) // avoid idle 0 which get the wait stuck for multiple seconds measureTimeMillis { waitForIdle(idleTimeout) }.let { Log.d(logTag, "waited $it millis for IDLE") } for (i in (0 until 10)) { pressRecentApps() // Cannot use wait for changes because it waits some interact-able element delay(100) // avoid idle 0 which get the wait stuck for multiple seconds measureTimeMillis { waitForIdle(idleTimeout) }.let { Log.d(logTag, "waited $it millis for IDLE") } Log.d(logTag, "Current package name $currentPackageName") if (currentPackageName == currentPackage) break } } private suspend fun UiDevice.launchApp(appPackageName: String, env: UiAutomationEnvironment, launchActivityDelay: Long, waitTime: Long): Boolean { var success = false // Launch the app val intent = env.context.packageManager .getLaunchIntentForPackage(appPackageName) // Clear out any previous instances intent?.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK) // Update environment env.launchedMainActivity = try { intent?.component?.className ?: "" } catch (e: IllegalStateException) { "" } debugOut("determined launch-able main activity for pkg=${env.launchedMainActivity}",debugFetch) measureTimeMillis { env.context.startActivity(intent) // Wait for the app to appear wait(Until.hasObject(By.pkg(appPackageName).depth(0)), waitTime) delay(launchActivityDelay) success = UiHierarchy.waitFor(env, interactiveTimeout, actableAppElem) // mute audio after app launch (for very annoying apps we may need a contentObserver listening on audio setting changes) val audio = env.context.getSystemService(Context.AUDIO_SERVICE) as AudioManager audio.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_MUTE,0) audio.adjustStreamVolume(AudioManager.STREAM_RING, AudioManager.ADJUST_MUTE,0) audio.adjustStreamVolume(AudioManager.STREAM_ALARM, AudioManager.ADJUST_MUTE,0) }.also { Log.d(logTag, "TIME: load-time $it millis") } return success } private fun UiDevice.rotate(rotation: Int,automation: UiAutomation):Boolean{ val currRotation = (displayRotation * 90) Log.d(logTag, "Current rotation $currRotation") // Android supports the following rotations: // ROTATION_0 = 0; // ROTATION_90 = 1; // ROTATION_180 = 2; // ROTATION_270 = 3; // Thus, instead of 0-360 we have 0-3 // The rotation calculations is: [(current rotation in degrees + rotation) / 90] % 4 // Ex: curr = 90, rotation = 180 => [(90 + 360) / 90] % 4 => 1 val newRotation = ((currRotation + rotation) / 90) % 4 Log.d(logTag, "New rotation $newRotation") unfreezeRotation() return automation.setRotation(newRotation) }
gpl-3.0
3a3f1c4232154a624cbfa9f7bd975adf
40.471396
169
0.721459
3.588002
false
false
false
false
arturbosch/detekt
detekt-parser/src/test/kotlin/io/github/detekt/parser/KtCompilerSpec.kt
1
3712
package io.github.detekt.parser import io.github.detekt.psi.BASE_PATH import io.github.detekt.psi.LINE_SEPARATOR import io.github.detekt.psi.RELATIVE_PATH import io.github.detekt.test.utils.resourceAsPath import org.assertj.core.api.Assertions.assertThat import org.assertj.core.api.Assertions.assertThatIllegalArgumentException import org.jetbrains.kotlin.com.intellij.psi.PsiErrorElement import org.jetbrains.kotlin.psi.KtTreeVisitorVoid import org.spekframework.spek2.Spek import org.spekframework.spek2.lifecycle.CachingMode import org.spekframework.spek2.style.specification.describe class KtCompilerSpec : Spek({ describe("Kotlin Compiler") { val path = resourceAsPath("/cases") val ktCompiler by memoized(CachingMode.SCOPE) { KtCompiler() } it("Kotlin file with LF line separators has extra user data") { val ktFile = ktCompiler.compile(path, path.resolve("DefaultLf.kt")) assertThat(ktFile.getUserData(LINE_SEPARATOR)).isEqualTo("\n") assertThat(ktFile.getUserData(RELATIVE_PATH)) .isEqualTo("DefaultLf.kt") assertThat(ktFile.getUserData(BASE_PATH)) .endsWith("cases") } it("Kotlin file with CRLF line separators has extra user data") { val ktFile = ktCompiler.compile(path, path.resolve("DefaultCrLf.kt")) assertThat(ktFile.getUserData(LINE_SEPARATOR)).isEqualTo("\r\n") assertThat(ktFile.getUserData(RELATIVE_PATH)) .isEqualTo("DefaultCrLf.kt") assertThat(ktFile.getUserData(BASE_PATH)) .endsWith("cases") } it("Kotlin file with LF line separators does not store extra data for relative path if not provided") { val ktFile = ktCompiler.compile(null, path.resolve("DefaultLf.kt")) assertThat(ktFile.getUserData(LINE_SEPARATOR)).isEqualTo("\n") assertThat(ktFile.getUserData(RELATIVE_PATH)).isNull() assertThat(ktFile.getUserData(BASE_PATH)).isNull() } it("Kotlin file with CRLF line separators does not store extra data for relative path if not provided") { val ktFile = ktCompiler.compile(null, path.resolve("DefaultCrLf.kt")) assertThat(ktFile.getUserData(LINE_SEPARATOR)).isEqualTo("\r\n") assertThat(ktFile.getUserData(RELATIVE_PATH)).isNull() assertThat(ktFile.getUserData(BASE_PATH)).isNull() } it("throws an exception for an invalid sub path") { assertThatIllegalArgumentException() .isThrownBy { ktCompiler.compile(path, path) } .withMessageStartingWith("Given sub path (") .withMessageEndingWith(") should be a regular file!") } it("parses with errors for non kotlin files") { val cssPath = resourceAsPath("css") val ktFile = ktCompiler.compile(cssPath, cssPath.resolve("test.css")) val errors = mutableListOf<PsiErrorElement>() ktFile.accept(object : KtTreeVisitorVoid() { override fun visitErrorElement(element: PsiErrorElement) { errors.add(element) } }) assertThat(errors).isNotEmpty() } } describe("line ending detection") { it("detects CRLF line endings") { assertThat("1\r\n2".determineLineSeparator()).isEqualTo("\r\n") } it("detects LF line endings") { assertThat("1\n2".determineLineSeparator()).isEqualTo("\n") } it("detects CR line endings") { assertThat("1\r2".determineLineSeparator()).isEqualTo("\r") } } })
apache-2.0
d23979d3f957fad5ecb619eaf87e9560
38.913978
113
0.643588
4.680958
false
false
false
false
wiltonlazary/kotlin-native
Interop/Runtime/src/native/kotlin/kotlinx/cinterop/ObjectiveCImpl.kt
1
8324
/* * Copyright 2010-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @file:Suppress("NOTHING_TO_INLINE") package kotlinx.cinterop import kotlin.native.* import kotlin.native.internal.ExportTypeInfo import kotlin.native.internal.ExportForCppRuntime import kotlin.native.internal.TypedIntrinsic import kotlin.native.internal.IntrinsicType import kotlin.native.internal.FilterExceptions interface ObjCObject interface ObjCClass : ObjCObject interface ObjCClassOf<T : ObjCObject> : ObjCClass // TODO: T should be added to ObjCClass and all meta-classes instead. typealias ObjCObjectMeta = ObjCClass interface ObjCProtocol : ObjCObject @ExportTypeInfo("theForeignObjCObjectTypeInfo") @kotlin.native.internal.Frozen internal open class ForeignObjCObject : kotlin.native.internal.ObjCObjectWrapper abstract class ObjCObjectBase protected constructor() : ObjCObject { @Target(AnnotationTarget.CONSTRUCTOR) @Retention(AnnotationRetention.SOURCE) annotation class OverrideInit } abstract class ObjCObjectBaseMeta protected constructor() : ObjCObjectBase(), ObjCObjectMeta {} fun optional(): Nothing = throw RuntimeException("Do not call me!!!") @Deprecated( "Add @OverrideInit to constructor to make it override Objective-C initializer", level = DeprecationLevel.ERROR ) @TypedIntrinsic(IntrinsicType.OBJC_INIT_BY) external fun <T : ObjCObjectBase> T.initBy(constructorCall: T): T @kotlin.native.internal.ExportForCompiler private fun ObjCObjectBase.superInitCheck(superInitCallResult: ObjCObject?) { if (superInitCallResult == null) throw RuntimeException("Super initialization failed") if (superInitCallResult.objcPtr() != this.objcPtr()) throw UnsupportedOperationException("Super initializer has replaced object") } internal fun <T : Any?> Any?.uncheckedCast(): T = @Suppress("UNCHECKED_CAST") (this as T) // Note: if this is called for non-frozen object on a wrong worker, the program will terminate. @SymbolName("Kotlin_Interop_refFromObjC") external fun <T> interpretObjCPointerOrNull(objcPtr: NativePtr): T? @ExportForCppRuntime inline fun <T : Any> interpretObjCPointer(objcPtr: NativePtr): T = interpretObjCPointerOrNull<T>(objcPtr)!! @SymbolName("Kotlin_Interop_refToObjC") external fun Any?.objcPtr(): NativePtr @SymbolName("Kotlin_Interop_createKotlinObjectHolder") external fun createKotlinObjectHolder(any: Any?): NativePtr // Note: if this is called for non-frozen underlying ref on a wrong worker, the program will terminate. inline fun <reified T : Any> unwrapKotlinObjectHolder(holder: Any?): T { return unwrapKotlinObjectHolderImpl(holder!!.objcPtr()) as T } @PublishedApi @SymbolName("Kotlin_Interop_unwrapKotlinObjectHolder") external internal fun unwrapKotlinObjectHolderImpl(ptr: NativePtr): Any class ObjCObjectVar<T>(rawPtr: NativePtr) : CVariable(rawPtr) { companion object : CVariable.Type(pointerSize.toLong(), pointerSize) } class ObjCNotImplementedVar<T : Any?>(rawPtr: NativePtr) : CVariable(rawPtr) { companion object : CVariable.Type(pointerSize.toLong(), pointerSize) } var <T : Any?> ObjCNotImplementedVar<T>.value: T get() = TODO() set(value) = TODO() typealias ObjCStringVarOf<T> = ObjCNotImplementedVar<T> typealias ObjCBlockVar<T> = ObjCNotImplementedVar<T> @TypedIntrinsic(IntrinsicType.OBJC_CREATE_SUPER_STRUCT) @PublishedApi internal external fun createObjCSuperStruct(receiver: NativePtr, superClass: NativePtr): NativePtr @Target(AnnotationTarget.CLASS) @Retention(AnnotationRetention.BINARY) annotation class ExternalObjCClass(val protocolGetter: String = "", val binaryName: String = "") @Target(AnnotationTarget.FUNCTION, AnnotationTarget.PROPERTY_GETTER, AnnotationTarget.PROPERTY_SETTER) @Retention(AnnotationRetention.BINARY) annotation class ObjCMethod(val selector: String, val encoding: String, val isStret: Boolean = false) @Target(AnnotationTarget.CONSTRUCTOR) @Retention(AnnotationRetention.BINARY) annotation class ObjCConstructor(val initSelector: String, val designated: Boolean) @Target(AnnotationTarget.FUNCTION) @Retention(AnnotationRetention.BINARY) annotation class ObjCFactory(val selector: String, val encoding: String, val isStret: Boolean = false) @Target(AnnotationTarget.FILE) @Retention(AnnotationRetention.BINARY) annotation class InteropStubs() @PublishedApi @Target(AnnotationTarget.FUNCTION) @Retention(AnnotationRetention.SOURCE) internal annotation class ObjCMethodImp(val selector: String, val encoding: String) @PublishedApi @TypedIntrinsic(IntrinsicType.OBJC_GET_SELECTOR) internal external fun objCGetSelector(selector: String): COpaquePointer @kotlin.native.internal.ExportForCppRuntime("Kotlin_Interop_getObjCClass") private fun getObjCClassByName(name: NativePtr): NativePtr { val result = objc_lookUpClass(name) if (result == nativeNullPtr) { val className = interpretCPointer<ByteVar>(name)!!.toKString() val message = """Objective-C class '$className' not found. |Ensure that the containing framework or library was linked.""".trimMargin() throw RuntimeException(message) } return result } @kotlin.native.internal.ExportForCompiler private fun allocObjCObject(clazz: NativePtr): NativePtr { val rawResult = objc_allocWithZone(clazz) if (rawResult == nativeNullPtr) { throw OutOfMemoryError("Unable to allocate Objective-C object") } // Note: `objc_allocWithZone` returns retained pointer, and thus it must be balanced by the caller. return rawResult } @TypedIntrinsic(IntrinsicType.OBJC_GET_OBJC_CLASS) @kotlin.native.internal.ExportForCompiler private external fun <T : ObjCObject> getObjCClass(): NativePtr @PublishedApi @TypedIntrinsic(IntrinsicType.OBJC_GET_MESSENGER) internal external fun getMessenger(superClass: NativePtr): COpaquePointer? @PublishedApi @TypedIntrinsic(IntrinsicType.OBJC_GET_MESSENGER_STRET) internal external fun getMessengerStret(superClass: NativePtr): COpaquePointer? internal class ObjCWeakReferenceImpl : kotlin.native.ref.WeakReferenceImpl() { @SymbolName("Konan_ObjCInterop_getWeakReference") external override fun get(): Any? } @SymbolName("Konan_ObjCInterop_initWeakReference") private external fun ObjCWeakReferenceImpl.init(objcPtr: NativePtr) @kotlin.native.internal.ExportForCppRuntime internal fun makeObjCWeakReferenceImpl(objcPtr: NativePtr): ObjCWeakReferenceImpl { val result = ObjCWeakReferenceImpl() result.init(objcPtr) return result } // Konan runtme: @Deprecated("Use plain Kotlin cast of String to NSString", level = DeprecationLevel.ERROR) @SymbolName("Kotlin_Interop_CreateNSStringFromKString") external fun CreateNSStringFromKString(str: String?): NativePtr @Deprecated("Use plain Kotlin cast of NSString to String", level = DeprecationLevel.ERROR) @SymbolName("Kotlin_Interop_CreateKStringFromNSString") external fun CreateKStringFromNSString(ptr: NativePtr): String? @PublishedApi @SymbolName("Kotlin_Interop_CreateObjCObjectHolder") internal external fun createObjCObjectHolder(ptr: NativePtr): Any? // Objective-C runtime: @SymbolName("objc_retainAutoreleaseReturnValue") external fun objc_retainAutoreleaseReturnValue(ptr: NativePtr): NativePtr @SymbolName("Kotlin_objc_autoreleasePoolPush") external fun objc_autoreleasePoolPush(): NativePtr @SymbolName("Kotlin_objc_autoreleasePoolPop") external fun objc_autoreleasePoolPop(ptr: NativePtr) @SymbolName("Kotlin_objc_allocWithZone") @FilterExceptions private external fun objc_allocWithZone(clazz: NativePtr): NativePtr @SymbolName("Kotlin_objc_retain") external fun objc_retain(ptr: NativePtr): NativePtr @SymbolName("Kotlin_objc_release") external fun objc_release(ptr: NativePtr) @SymbolName("Kotlin_objc_lookUpClass") external fun objc_lookUpClass(name: NativePtr): NativePtr
apache-2.0
900489e46050007923c7c489d2d7992c
36.327354
127
0.790846
4.270908
false
false
false
false
06needhamt/Neuroph-Intellij-Plugin
neuroph-plugin/src/com/thomas/needham/neurophidea/designer/psi/snnet/compiler/generator/SnnetGenerator.kt
1
3798
/* The MIT License (MIT) Copyright (c) 2016 Tom Needham Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.thomas.needham.neurophidea.designer.psi.snnet.compiler.generator import com.intellij.openapi.ui.Messages import com.thomas.needham.neurophidea.Tuple3 import com.thomas.needham.neurophidea.actions.CompileSnnetFileAction import com.thomas.needham.neurophidea.datastructures.LearningRules import com.thomas.needham.neurophidea.datastructures.NetworkConfiguration import com.thomas.needham.neurophidea.datastructures.NetworkTypes import com.thomas.needham.neurophidea.datastructures.TransferFunctions import com.thomas.needham.neurophidea.designer.psi.snnet.compiler.parser.SnnetProperties import java.io.* /** * Created by thoma on 01/07/2016. */ class SnnetGenerator { val networkDesc: SnnetProperties<Any>? var networkConf: NetworkConfiguration? val ToIntArray: (Array<Double>) -> Array<Int> = { e -> val arr = IntArray(e.size) for (i in 0..e.size - 1) { arr[i] = e[i].toInt() } arr.toTypedArray() } constructor(networkDesc: SnnetProperties<Any>) { this.networkDesc = networkDesc this.networkConf = GenerateNetwork() } private fun GenerateNetwork(): NetworkConfiguration? { var name: String = "" var type: NetworkTypes.Types = NetworkTypes.Types.values()[0] var rule: LearningRules.Rules = LearningRules.Rules.values()[0] var function: TransferFunctions.Functions = TransferFunctions.Functions.values()[0] var layers: Array<Double>? = null for (prop: Tuple3<*, *, *> in networkDesc?.properties!!) { when (prop.valueY as String) { "NetworkName" -> name = prop.valueZ as String "NetworkType" -> type = { NetworkTypes.Types.values()[NetworkTypes.classNames.indexOf(prop.valueZ as String)] }() "NetworkLearningRule" -> rule = { LearningRules.Rules.values()[LearningRules.classNames.indexOf(prop.valueZ as String)] }() "NetworkTransferFunction" -> function = { TransferFunctions.Functions.values()[TransferFunctions.classNames.indexOf(prop.valueZ as String)] }() "NetworkLayers" -> layers = prop.valueZ as Array<Double>? } } return NetworkConfiguration(name, type, ToIntArray(layers!!), rule, function, "", "", "${CompileSnnetFileAction.projectDirectory}") } fun SaveNetwork(path: String) { val file = File(path) try { val fos = FileOutputStream(file) val oos = ObjectOutputStream(fos) oos.writeObject(networkConf) oos.close() } catch (ioe: IOException) { ioe.printStackTrace(System.err) Messages.showErrorDialog(CompileSnnetFileAction.project, "Error Writing Compiled Network To File", "Error") return } catch (fnfe: FileNotFoundException) { fnfe.printStackTrace(System.err) Messages.showErrorDialog(CompileSnnetFileAction.project, "File Does Not Exist ${file.path}", "Error") return } } }
mit
ce3f34824658b4e1c3fc3dda69ae7e0c
41.211111
147
0.76277
3.923554
false
false
false
false
rsiebert/TVHClient
app/src/main/java/org/tvheadend/tvhclient/ui/features/dvr/series_recordings/SeriesRecordingListFragment.kt
1
11122
package org.tvheadend.tvhclient.ui.features.dvr.series_recordings import android.os.Bundle import android.view.* import android.widget.Filter import androidx.appcompat.widget.PopupMenu import androidx.fragment.app.FragmentTransaction import androidx.lifecycle.Lifecycle import androidx.lifecycle.ViewModelProvider import androidx.recyclerview.widget.LinearLayoutManager import org.tvheadend.data.entity.SeriesRecording import org.tvheadend.tvhclient.R import org.tvheadend.tvhclient.databinding.RecyclerviewFragmentBinding import org.tvheadend.tvhclient.ui.base.BaseFragment import org.tvheadend.tvhclient.ui.common.* import org.tvheadend.tvhclient.ui.common.interfaces.RecyclerViewClickInterface import org.tvheadend.tvhclient.ui.common.interfaces.SearchRequestInterface import org.tvheadend.tvhclient.util.extensions.gone import org.tvheadend.tvhclient.util.extensions.visible import org.tvheadend.tvhclient.util.extensions.visibleOrGone import timber.log.Timber import java.util.concurrent.CopyOnWriteArrayList class SeriesRecordingListFragment : BaseFragment(), RecyclerViewClickInterface, SearchRequestInterface, Filter.FilterListener { private lateinit var binding: RecyclerviewFragmentBinding private lateinit var seriesRecordingViewModel: SeriesRecordingViewModel private lateinit var recyclerViewAdapter: SeriesRecordingRecyclerViewAdapter override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { binding = RecyclerviewFragmentBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) seriesRecordingViewModel = ViewModelProvider(requireActivity())[SeriesRecordingViewModel::class.java] arguments?.let { seriesRecordingViewModel.selectedListPosition = it.getInt("listPosition") } recyclerViewAdapter = SeriesRecordingRecyclerViewAdapter(isDualPane, this, htspVersion) binding.recyclerView.layoutManager = LinearLayoutManager(activity) binding.recyclerView.adapter = recyclerViewAdapter binding.recyclerView.gone() binding.searchProgress.visibleOrGone(baseViewModel.isSearchActive) seriesRecordingViewModel.recordings.observe(viewLifecycleOwner, { recordings -> if (recordings != null) { recyclerViewAdapter.addItems(recordings) observeSearchQuery() } binding.recyclerView.visible() showStatusInToolbar() activity?.invalidateOptionsMenu() if (isDualPane && recyclerViewAdapter.itemCount > 0) { showRecordingDetails(seriesRecordingViewModel.selectedListPosition) } }) } private fun observeSearchQuery() { Timber.d("Observing search query") baseViewModel.searchQueryLiveData.observe(viewLifecycleOwner, { query -> if (query.isNotEmpty()) { Timber.d("View model returned search query '$query'") onSearchRequested(query) } else { Timber.d("View model returned empty search query") onSearchResultsCleared() } }) } private fun showStatusInToolbar() { context?.let { if (!baseViewModel.isSearchActive) { toolbarInterface.setTitle(getString(R.string.series_recordings)) toolbarInterface.setSubtitle(it.resources.getQuantityString(R.plurals.items, recyclerViewAdapter.itemCount, recyclerViewAdapter.itemCount)) } else { toolbarInterface.setTitle(getString(R.string.search_results)) toolbarInterface.setSubtitle(it.resources.getQuantityString(R.plurals.series_recordings, recyclerViewAdapter.itemCount, recyclerViewAdapter.itemCount)) } } } override fun onOptionsItemSelected(item: MenuItem): Boolean { val ctx = context ?: return super.onOptionsItemSelected(item) return when (item.itemId) { R.id.menu_add_recording -> return addNewSeriesRecording(requireActivity()) R.id.menu_remove_all_recordings -> showConfirmationToRemoveAllSeriesRecordings(ctx, CopyOnWriteArrayList(recyclerViewAdapter.items)) else -> super.onOptionsItemSelected(item) } } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { super.onCreateOptionsMenu(menu, inflater) inflater.inflate(R.menu.recording_list_options_menu, menu) } override fun onPrepareOptionsMenu(menu: Menu) { super.onPrepareOptionsMenu(menu) if (sharedPreferences.getBoolean("delete_all_recordings_menu_enabled", resources.getBoolean(R.bool.pref_default_delete_all_recordings_menu_enabled)) && recyclerViewAdapter.itemCount > 1 && isConnectionToServerAvailable) { menu.findItem(R.id.menu_remove_all_recordings)?.isVisible = true } menu.findItem(R.id.menu_add_recording)?.isVisible = isUnlocked && isConnectionToServerAvailable menu.findItem(R.id.menu_search)?.isVisible = recyclerViewAdapter.itemCount > 0 menu.findItem(R.id.media_route_menu_item)?.isVisible = false } private fun showRecordingDetails(position: Int) { seriesRecordingViewModel.selectedListPosition = position recyclerViewAdapter.setPosition(position) val recording = recyclerViewAdapter.getItem(position) if (recording == null || !isVisible) { return } val fm = activity?.supportFragmentManager if (!isDualPane) { val fragment = SeriesRecordingDetailsFragment.newInstance(recording.id) fm?.beginTransaction()?.also { it.replace(R.id.main, fragment) it.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE) it.addToBackStack(null) it.commit() } } else { var fragment = activity?.supportFragmentManager?.findFragmentById(R.id.details) if (fragment !is SeriesRecordingDetailsFragment) { fragment = SeriesRecordingDetailsFragment.newInstance(recording.id) // Check the lifecycle state to avoid committing the transaction // after the onSaveInstance method was already called which would // trigger an illegal state exception. if (lifecycle.currentState.isAtLeast(Lifecycle.State.RESUMED)) { fm?.beginTransaction()?.also { it.replace(R.id.details, fragment) it.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE) it.commit() } } } else if (seriesRecordingViewModel.currentIdLiveData.value != recording.id) { seriesRecordingViewModel.currentIdLiveData.value = recording.id } } } private fun showPopupMenu(view: View, position: Int) { val ctx = context ?: return val seriesRecording = recyclerViewAdapter.getItem(position) ?: return val popupMenu = PopupMenu(ctx, view) popupMenu.menuInflater.inflate(R.menu.series_recordings_popup_menu, popupMenu.menu) popupMenu.menuInflater.inflate(R.menu.external_search_options_menu, popupMenu.menu) preparePopupOrToolbarSearchMenu(popupMenu.menu, seriesRecording.title, isConnectionToServerAvailable) popupMenu.menu.findItem(R.id.menu_edit_recording)?.isVisible = isUnlocked popupMenu.menu.findItem(R.id.menu_disable_recording)?.isVisible = htspVersion >= 19 && isUnlocked && seriesRecording.isEnabled popupMenu.menu.findItem(R.id.menu_enable_recording)?.isVisible = htspVersion >= 19 && isUnlocked && !seriesRecording.isEnabled popupMenu.setOnMenuItemClickListener { item -> when (item.itemId) { R.id.menu_edit_recording -> return@setOnMenuItemClickListener editSelectedSeriesRecording(requireActivity(), seriesRecording.id) R.id.menu_remove_recording -> return@setOnMenuItemClickListener showConfirmationToRemoveSelectedSeriesRecording(ctx, seriesRecording, null) R.id.menu_disable_recording -> return@setOnMenuItemClickListener enableSeriesRecording(seriesRecording, false) R.id.menu_enable_recording -> return@setOnMenuItemClickListener enableSeriesRecording(seriesRecording, true) R.id.menu_search_imdb -> return@setOnMenuItemClickListener searchTitleOnImdbWebsite(ctx, seriesRecording.title) R.id.menu_search_fileaffinity -> return@setOnMenuItemClickListener searchTitleOnFileAffinityWebsite(ctx, seriesRecording.title) R.id.menu_search_youtube -> return@setOnMenuItemClickListener searchTitleOnYoutube(ctx, seriesRecording.title) R.id.menu_search_google -> return@setOnMenuItemClickListener searchTitleOnGoogle(ctx, seriesRecording.title) R.id.menu_search_epg -> return@setOnMenuItemClickListener searchTitleInTheLocalDatabase(requireActivity(), baseViewModel, seriesRecording.title) else -> return@setOnMenuItemClickListener false } } popupMenu.show() } private fun enableSeriesRecording(seriesRecording: SeriesRecording, enabled: Boolean): Boolean { val intent = seriesRecordingViewModel.getIntentData(requireContext(), seriesRecording) intent.action = "updateAutorecEntry" intent.putExtra("id", seriesRecording.id) intent.putExtra("enabled", if (enabled) 1 else 0) activity?.startService(intent) return true } override fun onClick(view: View, position: Int) { showRecordingDetails(position) } override fun onLongClick(view: View, position: Int): Boolean { showPopupMenu(view, position) return true } override fun onFilterComplete(i: Int) { binding.searchProgress.gone() showStatusInToolbar() // Preselect the first result item in the details screen if (isDualPane) { when { recyclerViewAdapter.itemCount > seriesRecordingViewModel.selectedListPosition -> { showRecordingDetails(seriesRecordingViewModel.selectedListPosition) } recyclerViewAdapter.itemCount <= seriesRecordingViewModel.selectedListPosition -> { showRecordingDetails(0) } recyclerViewAdapter.itemCount == 0 -> { removeDetailsFragment() } } } } override fun onSearchRequested(query: String) { recyclerViewAdapter.filter.filter(query, this) } override fun onSearchResultsCleared() { recyclerViewAdapter.filter.filter("", this) } override fun getQueryHint(): String { return getString(R.string.search_series_recordings) } }
gpl-3.0
8b632378657e41b069e263fb4befa409
46.32766
167
0.690433
5.45999
false
false
false
false
marciogranzotto/mqtt-painel-kotlin
app/src/main/java/com/granzotto/mqttpainel/presenters/SensorsCardPresenter.kt
1
1810
package com.granzotto.mqttpainel.presenters import com.granzotto.mqttpainel.fragments.SensorsFragment import com.granzotto.mqttpainel.models.SensorObj import com.pawegio.kandroid.i import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.CompositeDisposable import io.realm.Realm import org.eclipse.paho.client.mqttv3.MqttMessage /** * Created by marciogranzotto on 09/01/17. */ class SensorsCardPresenter constructor(var view: SensorsFragment?) { private var realm = Realm.getDefaultInstance() private var compositeDisposable = CompositeDisposable() fun onDestroy() { view = null } fun requestSensors() { realm?.where(SensorObj::class.java)?.findAll() ?.asFlowable() ?.distinctUntilChanged() ?.observeOn(AndroidSchedulers.mainThread()) ?.subscribe({ view?.onSensorsSuccess(it) }, { it.printStackTrace() })?.let { compositeDisposable.add(it) } } fun messageReceived(topic: String, message: MqttMessage?) { i { "messageReceived called" } if (message == null) return realm?.where(SensorObj::class.java)?.equalTo("topic", topic)?.findFirst() ?.asFlowable<SensorObj>() ?.distinctUntilChanged() ?.observeOn(AndroidSchedulers.mainThread()) ?.subscribe({ realm?.beginTransaction() it.value = message.toString() realm?.commitTransaction() i { it.toString() } view?.reloadSensor(it) }, { it.printStackTrace() })?.let { compositeDisposable.add(it) } } }
gpl-3.0
c8e54a70b6f0f0b1a994436e54976f8d
32.518519
81
0.591713
4.93188
false
false
false
false
wiltonlazary/kotlin-native
build-tools/src/main/kotlin/org/jetbrains/kotlin/MPPTools.kt
1
11712
/* * Copyright 2010-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/LICENSE.txt file. */ @file:JvmName("MPPTools") package org.jetbrains.kotlin import groovy.lang.Closure import org.gradle.api.Project import org.gradle.api.Task import org.gradle.api.tasks.TaskState import org.gradle.api.execution.TaskExecutionListener import org.jetbrains.kotlin.gradle.plugin.KotlinTargetPreset import org.jetbrains.kotlin.gradle.plugin.mpp.NativeBuildType import org.jetbrains.kotlin.gradle.tasks.KotlinNativeLink import org.jetbrains.kotlin.konan.target.HostManager import org.jetbrains.report.* import org.jetbrains.report.json.* import java.nio.file.Paths import java.io.File import java.io.FileInputStream import java.io.BufferedOutputStream import java.io.BufferedInputStream import java.net.HttpURLConnection import java.net.URL import java.util.Base64 /* * This file includes short-cuts that may potentially be implemented in Kotlin MPP Gradle plugin in the future. */ // Short-cuts for mostly used paths. @get:JvmName("mingwPath") val mingwPath by lazy { System.getenv("MINGW64_DIR") ?: "c:/msys64/mingw64" } @get:JvmName("kotlinNativeDataPath") val kotlinNativeDataPath by lazy { System.getenv("KONAN_DATA_DIR") ?: Paths.get(userHome, ".konan").toString() } // A short-cut for evaluation of the default host Kotlin/Native preset. @JvmOverloads fun defaultHostPreset( subproject: Project, whitelist: List<KotlinTargetPreset<*>> = listOf(subproject.kotlin.presets.macosX64, subproject.kotlin.presets.linuxX64, subproject.kotlin.presets.mingwX64) ): KotlinTargetPreset<*> { if (whitelist.isEmpty()) throw Exception("Preset whitelist must not be empty in Kotlin/Native ${subproject.displayName}.") val presetCandidate = when { PlatformInfo.isMac() -> subproject.kotlin.presets.macosX64 PlatformInfo.isLinux() -> subproject.kotlin.presets.linuxX64 PlatformInfo.isWindows() -> subproject.kotlin.presets.mingwX64 else -> null } return if (presetCandidate != null && presetCandidate in whitelist) presetCandidate else throw Exception("Host OS '$hostOs' is not supported in Kotlin/Native ${subproject.displayName}.") } fun getNativeProgramExtension(): String = when { PlatformInfo.isMac() -> ".kexe" PlatformInfo.isLinux() -> ".kexe" PlatformInfo.isWindows() -> ".exe" else -> error("Unknown host") } fun getFileSize(filePath: String): Long? { val file = File(filePath) return if (file.exists()) file.length() else null } fun getCodeSizeBenchmark(programName: String, filePath: String): BenchmarkResult { val codeSize = getFileSize(filePath) return BenchmarkResult(programName, codeSize?. let { BenchmarkResult.Status.PASSED } ?: run { BenchmarkResult.Status.FAILED }, codeSize?.toDouble() ?: 0.0, BenchmarkResult.Metric.CODE_SIZE, codeSize?.toDouble() ?: 0.0, 1, 0) } fun toCodeSizeBenchmark(metricDescription: String, status: String, programName: String): BenchmarkResult { if (!metricDescription.startsWith("CODE_SIZE")) { error("Wrong metric is used as code size.") } val codeSize = metricDescription.split(' ')[1].toDouble() return BenchmarkResult(programName, if (status == "PASSED") BenchmarkResult.Status.PASSED else BenchmarkResult.Status.FAILED, codeSize, BenchmarkResult.Metric.CODE_SIZE, codeSize, 1, 0) } // Create benchmarks json report based on information get from gradle project fun createJsonReport(projectProperties: Map<String, Any>): String { fun getValue(key: String): String = projectProperties[key] as? String ?: "unknown" val machine = Environment.Machine(getValue("cpu"), getValue("os")) val jdk = Environment.JDKInstance(getValue("jdkVersion"), getValue("jdkVendor")) val env = Environment(machine, jdk) val flags = (projectProperties["flags"] ?: emptyList<String>()) as List<String> val backend = Compiler.Backend(Compiler.backendTypeFromString(getValue("type"))!! , getValue("compilerVersion"), flags) val kotlin = Compiler(backend, getValue("kotlinVersion")) val benchDesc = getValue("benchmarks") val benchmarksArray = JsonTreeParser.parse(benchDesc) val benchmarks = parseBenchmarksArray(benchmarksArray) .union(projectProperties["compileTime"] as List<BenchmarkResult>).union( listOf(projectProperties["codeSize"] as? BenchmarkResult).filterNotNull()).toList() val report = BenchmarksReport(env, benchmarks, kotlin) return report.toJson() } fun mergeReports(reports: List<File>): String { val reportsToMerge = reports.filter { it.exists() }.map { val json = it.inputStream().bufferedReader().use { it.readText() } val reportElement = JsonTreeParser.parse(json) BenchmarksReport.create(reportElement) } val structuredReports = mutableMapOf<String, MutableList<BenchmarksReport>>() reportsToMerge.map { it.compiler.backend.flags.joinToString() to it }.forEach { structuredReports.getOrPut(it.first) { mutableListOf<BenchmarksReport>() }.add(it.second) } val jsons = structuredReports.map { (_, value) -> value.reduce { result, it -> result + it }.toJson() } return when(jsons.size) { 0 -> "" 1 -> jsons[0] else -> jsons.joinToString(prefix = "[", postfix = "]") } } fun getCompileOnlyBenchmarksOpts(project: Project, defaultCompilerOpts: List<String>): List<String> { val dist = project.file(project.findProperty("kotlin.native.home") ?: "dist") val useCache = !project.hasProperty("disableCompilerCaches") val cacheOption = "-Xcache-directory=$dist/klib/cache/${HostManager.host.name}-gSTATIC" .takeIf { useCache && PlatformInfo.isMac() } // TODO: remove target condition when we have cache support for other targets. return (project.findProperty("nativeBuildType") as String?)?.let { if (it.equals("RELEASE", true)) listOf("-opt") else if (it.equals("DEBUG", true)) listOfNotNull("-g", cacheOption) else listOf() } ?: defaultCompilerOpts + listOfNotNull(cacheOption?.takeIf { !defaultCompilerOpts.contains("-opt") }) } // Find file with set name in directory. fun findFile(fileName: String, directory: String): String? = File(directory).walkTopDown().filter { !it.absolutePath.contains(".dSYM") } .find { it.name == fileName }?.getAbsolutePath() fun uploadFileToArtifactory(url: String, project: String, artifactoryFilePath: String, filePath: String, password: String) { val uploadUrl = "$url/$project/$artifactoryFilePath" sendUploadRequest(uploadUrl, filePath, extraHeaders = listOf(Pair("X-JFrog-Art-Api", password))) } fun sendUploadRequest(url: String, fileName: String, username: String? = null, password: String? = null, extraHeaders: List<Pair<String, String>> = emptyList()) { val uploadingFile = File(fileName) val connection = URL(url).openConnection() as HttpURLConnection connection.doOutput = true connection.doInput = true connection.requestMethod = "PUT" connection.setRequestProperty("Content-type", "text/plain") if (username != null && password != null) { val auth = Base64.getEncoder().encode((username + ":" + password).toByteArray()).toString(Charsets.UTF_8) connection.addRequestProperty("Authorization", "Basic $auth") } extraHeaders.forEach { connection.addRequestProperty(it.first, it.second) } try { connection.connect() BufferedOutputStream(connection.outputStream).use { output -> BufferedInputStream(FileInputStream(uploadingFile)).use { input -> input.copyTo(output) } } val response = connection.responseMessage println("Upload request ended with ${connection.responseCode} - $response") } catch (t: Throwable) { error("Couldn't upload file $fileName to $url") } } // A short-cut to add a Kotlin/Native run task. @JvmOverloads fun createRunTask( subproject: Project, name: String, linkTask: Task, executable: String, outputFileName: String ): Task { return subproject.tasks.create(name, RunKotlinNativeTask::class.java, linkTask, executable, outputFileName) } fun getJvmCompileTime(subproject: Project,programName: String): BenchmarkResult = TaskTimerListener.getTimerListenerOfSubproject(subproject) .getBenchmarkResult(programName, listOf("compileKotlinMetadata", "jvmJar")) @JvmOverloads fun getNativeCompileTime(subproject: Project, programName: String, tasks: List<String> = listOf("linkBenchmarkReleaseExecutableNative")): BenchmarkResult = TaskTimerListener.getTimerListenerOfSubproject(subproject).getBenchmarkResult(programName, tasks) fun getCompileBenchmarkTime(subproject: Project, programName: String, tasksNames: Iterable<String>, repeats: Int, exitCodes: Map<String, Int>) = (1..repeats).map { number -> var time = 0.0 var status = BenchmarkResult.Status.PASSED tasksNames.forEach { time += TaskTimerListener.getTimerListenerOfSubproject(subproject).getTime("$it$number") status = if (exitCodes["$it$number"] != 0) BenchmarkResult.Status.FAILED else status } BenchmarkResult(programName, status, time, BenchmarkResult.Metric.COMPILE_TIME, time, number, 0) }.toList() fun toCompileBenchmark(metricDescription: String, status: String, programName: String): BenchmarkResult { if (!metricDescription.startsWith("COMPILE_TIME")) { error("Wrong metric is used as compile time.") } val time = metricDescription.split(' ')[1].toDouble() return BenchmarkResult(programName, if (status == "PASSED") BenchmarkResult.Status.PASSED else BenchmarkResult.Status.FAILED, time, BenchmarkResult.Metric.COMPILE_TIME, time, 1, 0) } // Class time tracker for all tasks. class TaskTimerListener: TaskExecutionListener { companion object { internal val timerListeners = mutableMapOf<String, TaskTimerListener>() internal fun getTimerListenerOfSubproject(subproject: Project) = timerListeners[subproject.name] ?: error("TimeListener for project ${subproject.name} wasn't set") } val tasksTimes = mutableMapOf<String, Double>() fun getBenchmarkResult(programName: String, tasksNames: List<String>): BenchmarkResult { val time = tasksNames.map { tasksTimes[it] ?: 0.0 }.sum() // TODO get this info from gradle plugin with exit code end stacktrace. val status = tasksNames.map { tasksTimes.containsKey(it) }.reduce { a, b -> a && b } return BenchmarkResult(programName, if (status) BenchmarkResult.Status.PASSED else BenchmarkResult.Status.FAILED, time, BenchmarkResult.Metric.COMPILE_TIME, time, 1, 0) } fun getTime(taskName: String) = tasksTimes[taskName] ?: 0.0 private var startTime = System.nanoTime() override fun beforeExecute(task: Task) { startTime = System.nanoTime() } override fun afterExecute(task: Task, taskState: TaskState) { tasksTimes[task.name] = (System.nanoTime() - startTime) / 1000.0 } } fun addTimeListener(subproject: Project) { val listener = TaskTimerListener() TaskTimerListener.timerListeners.put(subproject.name, listener) subproject.gradle.addListener(listener) }
apache-2.0
ab57abd7e24fa2a384631eb662d5260a
42.701493
159
0.696807
4.276013
false
false
false
false
DankBots/Mega-Gnar
src/main/kotlin/gg/octave/bot/commands/music/dj/Summon.kt
1
1893
package gg.octave.bot.commands.music.dj import gg.octave.bot.Launcher import gg.octave.bot.entities.framework.CheckVoiceState import gg.octave.bot.entities.framework.DJ import gg.octave.bot.entities.framework.MusicCog import gg.octave.bot.music.MusicLimitException import gg.octave.bot.utils.extensions.data import gg.octave.bot.utils.extensions.selfMember import gg.octave.bot.utils.extensions.voiceChannel import me.devoxin.flight.api.Context import me.devoxin.flight.api.annotations.Command import me.devoxin.flight.api.annotations.Greedy import net.dv8tion.jda.api.entities.VoiceChannel class Summon : MusicCog { override fun requirePlayer() = true @DJ @CheckVoiceState @Command(description = "Move the bot to another channel.") fun summon(ctx: Context, @Greedy channel: VoiceChannel?) { // val vc = channel // ?: ctx.voiceChannel // ?: return ctx.send("That's not a valid music channel. " + // "You can join a VC and run this command without arguments to make it join that channel.") // // if (vc == ctx.selfMember!!.voiceState?.channel) { // return ctx.send("That's the same channel as I'm currently in.") // } // // val data = ctx.data // // if (data.music.channels.isNotEmpty()) { // if (vc.id !in data.music.channels) { // return ctx.send("Can not join `${vc.name}`, it isn't one of the designated music channels.") // } // } val musicManager = try { Launcher.players.get(ctx.guild!!) } catch (e: MusicLimitException) { return e.sendToContext(ctx) } if (ctx.guild!!.audioManager.connectedChannel != null) { musicManager.moveAudioConnection(ctx.voiceChannel!!) } else { musicManager.openAudioConnection(ctx.voiceChannel!!, ctx) } } }
mit
c52aaa69308813f14cd2ac4905e7edea
36.117647
110
0.654517
3.855397
false
false
false
false
oboehm/jfachwert
src/main/kotlin/de/jfachwert/net/EMailAdresse.kt
1
6042
/* * Copyright (c) 2017-2020 by Oliver Boehm * * 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. * * (c)reated 23.06.2017 by oboehm ([email protected]) */ package de.jfachwert.net import de.jfachwert.KSimpleValidator import de.jfachwert.Text import de.jfachwert.post.Name import de.jfachwert.pruefung.NullValidator import de.jfachwert.pruefung.exception.InvalidValueException import org.apache.commons.lang3.StringUtils import java.util.* import java.util.regex.Pattern /** * Eine E-Mail-Adresse ist die eindeutige Absender- und Empfaengeradresse im * E-Mail-Verkehr. Sie besteht aus zwei Teilen, die durch ein @-Zeichen * voneinander getrennt sind: * * Der lokale Teil, im Englischen local-part genannt, * steht vor dem @-Zeichen. * * Der globale Teil, im Englischen domain-part genannt, * steht nach dem @-Zeichen. * * Bei der E-Mail-Adresse "[email protected]" ist "email" der lokale Teil * und "example.com" der globale Teil. * * @author oboehm * @since 0.3 (23.06.2017) */ open class EMailAdresse /** * Legt eine Instanz einer EMailAdresse an. Der Validator ist * hauptsaechlich fuer abgeleitete Klassen gedacht, die ihre eigene * Validierung mit einbringen wollen oder aus Performance-Gruenden * abschalten wollen. * * @param emailAdresse eine gueltige Adresse, z.B. "[email protected]" * @param validator SimpleValidator zur Adressen-Validierung */ @JvmOverloads constructor(emailAdresse: String, validator: KSimpleValidator<String> = VALIDATOR) : Text(validator.verify(emailAdresse)) { /** * Als Local Part wird der Teil einer E-Mail-Adresse bezeichnet, der die * Adresse innerhalb der Domain des E-Mail-Providers eindeutig bezeichnet. * Typischerweise entspricht der Lokalteil dem Benutzernamen (haeufig ein * Pseudonym) des Besitzers des E-Mail-Kontos. * * @return z.B. "Max.Mustermann" */ val localPart: String get() = StringUtils.substringBeforeLast(code, "@") /** * Der Domain Part, der hinter dem @-Zeichen steht und fuer den die * Syntaxregeln des Domain Name Systems gelten, besteht mindestens aus drei * Teilen: einem Hostnamen (z. B. ein Firmenname), einem Punkt und einer * Top-Level-Domain. * * @return z.B. "fachwert.de" */ val domainPart: Domainname get() = Domainname(StringUtils.substringAfterLast(code, "@")) /** * Liefert den Namensanteil der Email-Adresse als [Name] zurueck. * Kann dann eingesetzt werden, wenn die Email-Adresse nach dem Schema * "[email protected]" aufgebaut ist. * * @return z.B. "O. Boehm" als Name * @since 2.3 */ val name: Name get() { val name = capitalize(localPart, '.') return Name.of(name) } private fun capitalize(word: String, delimiter: Char): String { val parts = word.split(delimiter) var capitalized = "" for (s in parts) { capitalized += capitalize(s) + ' ' } return capitalized.trim() } private fun capitalize(word: String): String { return word.replaceFirstChar { if (it.isLowerCase()) it.titlecase() else it.toString() } } /** * Die Klasse EMailValidator validiert vornehmlich E-Mail-Adressen. * Urspruenglich war er eine separate Klasse, mit v2.2 wurde er anolog * zu den anderen Validatoren zur entsprechenden Klasse als innere Klasse * verschoben. * * @author oboehm * @since 0.3 (27.06.2017) */ class Validator /** * Dieser Konstruktor ist fuer abgeleitete Klassen gedacht, die das Pattern * fuer die Adress-Validierung ueberschreiben moechten. * * @param addressPattern Pattern fuer die Adress-Validerung */ protected constructor(private val addressPattern: Pattern) : KSimpleValidator<String> { /** * Hier wird der E-Mail-SimpleValidator mit einerm Pattern von * https://www.mkyong.com/regular-expressions/how-to-validate-email-address-with-regular-expression/ * aufgesetzt. */ constructor() : this(Pattern .compile("^[_A-Za-z0-9-+]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$")) { } /** * Fuehrt ein Pattern-basierte Pruefung der uebegebenen E-Mail-Adresse * durch. Schlaegt die Pruefung fehl, wird eine * [javax.validation.ValidationException] geworfen. * * @param value zu pruefende E-Mail-Adresse * @return die validierte E-Mail-Adresse (zur Weiterverarbeitung) */ override fun validate(value: String): String { val matcher = addressPattern.matcher(value) if (matcher.matches()) { return value } throw InvalidValueException(value, "email_address") } } companion object { private val VALIDATOR: KSimpleValidator<String> = Validator() private val WEAK_CACHE = WeakHashMap<String, EMailAdresse>() /** Null-Konstante fuer Initialisierungen. */ @JvmField val NULL = EMailAdresse("", NullValidator()) /** * Liefert einen EmailAdresse. * * @param name gueltige Email-Adresse * @return EMailAdresse */ @JvmStatic fun of(name: String): EMailAdresse { return WEAK_CACHE.computeIfAbsent(name) { emailAdresse: String -> EMailAdresse(emailAdresse) } } } }
apache-2.0
053624e809f7a93fb6d102d627fbd5d0
34.133721
137
0.652267
3.577265
false
false
false
false
ojacquemart/spring-kotlin-euro-bets
src/main/kotlin/org/ojacquemart/eurobets/firebase/initdb/i18n/I18ns.kt
2
891
package org.ojacquemart.eurobets.firebase.initdb.i18n import org.ojacquemart.eurobets.firebase.initdb.fixture.Phases import org.ojacquemart.eurobets.firebase.initdb.group.Groups object I18ns { val undefined = I18n("???", "???") private val groups = Groups.letters.associateBy({ "Group" + it }, { I18n("Groupe " + it, "Group " + it) }) private val phases = groups .plus("Round16" to I18n("Huitième de finale", "Round 16")) .plus("QuarterFinal" to I18n("Quarts de finale", "Quarter final")) .plus("SemiFinal" to I18n("Demi-finale", "Semi final")) .plus("Final" to I18n("Finale", "Final")) fun getGroup(groupCode: String) = groups.getOrElse(groupCode, { undefined }) fun getPhase(phase: String): I18n { val phaseCleaned = Phases.clean(phase) return phases.getOrElse(phaseCleaned, { undefined }) } }
unlicense
555db3287ea03ab7ed2fccde483a4883
37.695652
110
0.651685
3.503937
false
false
false
false
cashapp/sqldelight
sqldelight-idea-plugin/src/main/kotlin/app/cash/sqldelight/intellij/lang/SqlDelightFoldingBuilder.kt
1
5324
/* * Copyright (C) 2017 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package app.cash.sqldelight.intellij.lang import app.cash.sqldelight.core.psi.SqlDelightStmtIdentifier import app.cash.sqldelight.core.psi.SqldelightTypes import app.cash.sqldelight.intellij.util.prevSiblingOfType import com.alecstrong.sql.psi.core.psi.SqlCreateIndexStmt import com.alecstrong.sql.psi.core.psi.SqlCreateTriggerStmt import com.alecstrong.sql.psi.core.psi.SqlCreateViewStmt import com.alecstrong.sql.psi.core.psi.SqlTypes import com.intellij.lang.ASTNode import com.intellij.lang.folding.FoldingBuilder import com.intellij.lang.folding.FoldingDescriptor import com.intellij.openapi.editor.Document import com.intellij.openapi.project.DumbAware import com.intellij.psi.PsiElement import com.intellij.psi.PsiWhiteSpace import org.jetbrains.kotlin.psi.psiUtil.endOffset import org.jetbrains.kotlin.psi.psiUtil.getChildOfType class SqlDelightFoldingBuilder : FoldingBuilder, DumbAware { override fun buildFoldRegions(root: ASTNode, document: Document) = root.createFoldingDescriptors() private fun ASTNode.createFoldingDescriptors(): Array<FoldingDescriptor> { return getChildren(null) .filter { it.elementType == SqldelightTypes.STMT_LIST } .flatMap { val descriptors = mutableListOf<FoldingDescriptor>() val statements = it.getChildren(null).toList() for (statement in statements) { when (statement.elementType) { SqldelightTypes.IMPORT_STMT_LIST -> statement.psi.toImportListDescriptor()?.let(descriptors::add) SqlTypes.STMT -> { val psi = statement.psi val sqlStatement = statement.firstChildNode when (sqlStatement?.elementType) { SqlTypes.CREATE_TABLE_STMT -> psi.toCreateTableDescriptor(sqlStatement?.psi)?.let(descriptors::add) SqlTypes.CREATE_VIEW_STMT -> psi.toCreateViewDescriptor(sqlStatement?.psi)?.let(descriptors::add) SqlTypes.CREATE_TRIGGER_STMT -> psi.toCreateTriggerDescriptor(sqlStatement?.psi)?.let(descriptors::add) SqlTypes.CREATE_INDEX_STMT -> psi.toCreateIndexDescriptor(sqlStatement?.psi)?.let(descriptors::add) } val stmtIdentifier = psi.prevSiblingOfType<SqlDelightStmtIdentifier>() if (stmtIdentifier?.identifier() != null) { psi.toStatementDescriptor(stmtIdentifier)?.let(descriptors::add) } } } } return@flatMap descriptors } .toTypedArray() } private fun PsiElement.toCreateTableDescriptor(createTableStmt: PsiElement?): FoldingDescriptor? { val openingBraceElement = createTableStmt?.node?.findChildByType(SqlTypes.LP) ?: return null val start = openingBraceElement.startOffset val end = nextSibling?.endOffset ?: 0 if (start >= end) return null return FoldingDescriptor(this, start, end, null, "(...);") } private fun PsiElement.toCreateViewDescriptor(createViewStmt: PsiElement?): FoldingDescriptor? { val viewNameElement = (createViewStmt as? SqlCreateViewStmt)?.viewName ?: return null return toStatementDescriptor(viewNameElement) } private fun PsiElement.toCreateTriggerDescriptor( createTriggerStmt: PsiElement?, ): FoldingDescriptor? { val triggerNameElement = (createTriggerStmt as? SqlCreateTriggerStmt)?.triggerName ?: return null return toStatementDescriptor(triggerNameElement) } private fun PsiElement.toCreateIndexDescriptor(createIndexStmt: PsiElement?): FoldingDescriptor? { val indexNameElement = (createIndexStmt as? SqlCreateIndexStmt)?.indexName ?: return null return toStatementDescriptor(indexNameElement) } private fun PsiElement.toStatementDescriptor(stmtIdentifier: PsiElement?): FoldingDescriptor? { if (stmtIdentifier == null) return null if (nextSibling?.node?.elementType != SqlTypes.SEMI) return null val start = stmtIdentifier.endOffset val end = nextSibling.endOffset if (start >= end) return null return FoldingDescriptor(this, start, end, null, "...") } private fun PsiElement.toImportListDescriptor(): FoldingDescriptor? { if (children.size < 2) return null val whitespaceElement = firstChild.getChildOfType<PsiWhiteSpace>() ?: return null val start = whitespaceElement.endOffset val end = lastChild.endOffset if (start >= end) return null return FoldingDescriptor(this, start, end, null, "...") } override fun getPlaceholderText(node: ASTNode) = "..." override fun isCollapsedByDefault(node: ASTNode) = with(node) { elementType == SqldelightTypes.IMPORT_STMT_LIST && getChildren(null).size > 1 } }
apache-2.0
1b15c62a9b665b7e1b79d0f497bd23cf
41.592
100
0.719947
4.605536
false
false
false
false