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
GlimpseFramework/glimpse-framework
materials/src/main/kotlin/glimpse/materials/Plastic.kt
1
1946
package glimpse.materials import glimpse.Color import glimpse.cameras.Camera import glimpse.gles.delegates.DisposableLazyDelegate import glimpse.io.resource import glimpse.lights.Light import glimpse.models.Model import glimpse.shaders.Program import glimpse.shaders.shaderProgram /** * Plastic material. */ class Plastic(val diffuse: Color, val ambient: Color = diffuse, val specular: Color = Color.WHITE, val shininess: Float = 100f) : AbstractMaterial() { init { PlasticShaderHelper.registerDisposable() } override fun render(model: Model, camera: Camera, lights: List<Light>) { val mvpMatrix = camera.cameraMatrix * model.transformation() val viewMatrix = camera.view.viewMatrix val modelViewMatrix = viewMatrix * model.transformation() PlasticShaderHelper.use() PlasticShaderHelper["u_DiffuseColor"] = diffuse PlasticShaderHelper["u_AmbientColor"] = ambient PlasticShaderHelper["u_SpecularColor"] = specular PlasticShaderHelper["u_Shininess"] = shininess PlasticShaderHelper["u_MVPMatrix"] = mvpMatrix PlasticShaderHelper["u_MVMatrix"] = modelViewMatrix PlasticShaderHelper["u_ModelMatrix"] = model.transformation() PlasticShaderHelper["u_LightMatrix"] = viewMatrix.trimmed PlasticShaderHelper["u_NormalMatrix"] = modelViewMatrix.trimmed PlasticShaderHelper["u_Light"] = lights PlasticShaderHelper.drawMesh(model.mesh) } } internal object PlasticShaderHelper : ShaderHelper() { override val program: Program? by DisposableLazyDelegate { shaderProgram { vertexShader { PlasticShaderHelper.resource("Plastic_vertex.glsl").lines.joinToString(separator = "\n") { it } } fragmentShader { PlasticShaderHelper.resource("Plastic_fragment.glsl").lines.joinToString(separator = "\n") { it } } } } override val vertexPositionAttributeName = "a_VertexPosition" override val vertexTextureCoordinatesAttributeName = null override val vertexNormalAttributeName = "a_VertexNormal" }
apache-2.0
81081b4224c5e14fbe3c5a83e98e9ba8
33.75
150
0.776465
3.756757
false
false
false
false
b95505017/android-architecture-components
PagingSample/app/src/main/java/paging/android/example/com/pagingsample/CheeseAdapter.kt
1
2858
/* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package paging.android.example.com.pagingsample import android.arch.paging.PagedListAdapter import android.support.v7.recyclerview.extensions.DiffCallback import android.view.ViewGroup /** * A simple PagedListAdapter that binds Cheese items into CardViews. * <p> * PagedListAdapter is a RecyclerView.Adapter base class which can present the content of PagedLists * in a RecyclerView. It requests new pages as the user scrolls, and handles new PagedLists by * computing list differences on a background thread, and dispatching minimal, efficient updates to * the RecyclerView to ensure minimal UI thread work. * <p> * If you want to use your own Adapter base class, try using a PagedListAdapterHelper inside your * adapter instead. * * @see android.arch.paging.PagedListAdapter * @see android.arch.paging.PagedListAdapterHelper */ class CheeseAdapter : PagedListAdapter<Cheese, CheeseViewHolder>(diffCallback) { override fun onBindViewHolder(holder: CheeseViewHolder, position: Int) { holder.bindTo(getItem(position)) } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CheeseViewHolder = CheeseViewHolder(parent) companion object { /** * This diff callback informs the PagedListAdapter how to compute list differences when new * PagedLists arrive. * <p> * When you add a Cheese with the 'Add' button, the PagedListAdapter uses diffCallback to * detect there's only a single item difference from before, so it only needs to animate and * rebind a single view. * * @see android.support.v7.util.DiffUtil */ private val diffCallback = object : DiffCallback<Cheese>() { override fun areItemsTheSame(oldItem: Cheese, newItem: Cheese): Boolean = oldItem.id == newItem.id /** * Note that in kotlin, == checking on data classes compares all contents, but in Java, * typically you'll implement Object#equals, and use it to compare object contents. */ override fun areContentsTheSame(oldItem: Cheese, newItem: Cheese): Boolean = oldItem == newItem } } }
apache-2.0
460d27877de438d2582470f4f8449c5f
41.044118
100
0.701889
4.755408
false
false
false
false
icanit/mangafeed
app/src/main/java/eu/kanade/tachiyomi/ui/reader/ReaderActivity.kt
1
20285
package eu.kanade.tachiyomi.ui.reader import android.app.Dialog import android.content.Context import android.content.Intent import android.content.pm.ActivityInfo import android.content.res.Configuration import android.graphics.Color import android.os.Build import android.os.Bundle import android.support.v4.content.ContextCompat import android.view.* import android.view.WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE import android.view.animation.Animation import android.view.animation.AnimationUtils import android.widget.SeekBar import com.afollestad.materialdialogs.MaterialDialog import eu.kanade.tachiyomi.R import eu.kanade.tachiyomi.data.database.models.Chapter import eu.kanade.tachiyomi.data.database.models.Manga import eu.kanade.tachiyomi.data.preference.PreferencesHelper import eu.kanade.tachiyomi.data.preference.getOrDefault import eu.kanade.tachiyomi.data.source.model.Page import eu.kanade.tachiyomi.ui.base.activity.BaseRxActivity import eu.kanade.tachiyomi.ui.base.listener.SimpleAnimationListener import eu.kanade.tachiyomi.ui.base.listener.SimpleSeekBarListener import eu.kanade.tachiyomi.ui.reader.viewer.base.BaseReader import eu.kanade.tachiyomi.ui.reader.viewer.pager.horizontal.LeftToRightReader import eu.kanade.tachiyomi.ui.reader.viewer.pager.horizontal.RightToLeftReader import eu.kanade.tachiyomi.ui.reader.viewer.pager.vertical.VerticalReader import eu.kanade.tachiyomi.ui.reader.viewer.webtoon.WebtoonReader import eu.kanade.tachiyomi.util.GLUtil import eu.kanade.tachiyomi.util.toast import kotlinx.android.synthetic.main.activity_reader.* import kotlinx.android.synthetic.main.reader_menu.* import nucleus.factory.RequiresPresenter import rx.Subscription import rx.subscriptions.CompositeSubscription import timber.log.Timber import java.text.DecimalFormat @RequiresPresenter(ReaderPresenter::class) class ReaderActivity : BaseRxActivity<ReaderPresenter>() { companion object { @Suppress("unused") const val LEFT_TO_RIGHT = 1 const val RIGHT_TO_LEFT = 2 const val VERTICAL = 3 const val WEBTOON = 4 const val BLACK_THEME = 1 const val MENU_VISIBLE = "menu_visible" fun newIntent(context: Context): Intent { return Intent(context, ReaderActivity::class.java) } } private var viewer: BaseReader? = null private var uiFlags: Int = 0 lateinit var subscriptions: CompositeSubscription private set private var customBrightnessSubscription: Subscription? = null var readerTheme: Int = 0 private set var maxBitmapSize: Int = 0 private set private val decimalFormat = DecimalFormat("#.###") private var popupMenu: ReaderPopupMenu? = null private var nextChapterBtn: MenuItem? = null private var prevChapterBtn: MenuItem? = null private val volumeKeysEnabled by lazy { preferences.readWithVolumeKeys().getOrDefault() } val preferences: PreferencesHelper get() = presenter.prefs override fun onCreate(savedState: Bundle?) { super.onCreate(savedState) setContentView(R.layout.activity_reader) setupToolbar(toolbar) subscriptions = CompositeSubscription() initializeMenu() initializeSettings() if (savedState != null) { setMenuVisibility(savedState.getBoolean(MENU_VISIBLE), animate = false) } maxBitmapSize = GLUtil.getMaxTextureSize() } override fun onResume() { super.onResume() setSystemUiVisibility() } override fun onPause() { viewer?.let { presenter.currentPage = it.getActivePage() } super.onPause() } override fun onDestroy() { subscriptions.unsubscribe() popupMenu?.dismiss() viewer = null super.onDestroy() } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.reader, menu) nextChapterBtn = menu.findItem(R.id.action_next_chapter) prevChapterBtn = menu.findItem(R.id.action_previous_chapter) setAdjacentChaptersVisibility() return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.action_previous_chapter -> requestPreviousChapter() R.id.action_next_chapter -> requestNextChapter() else -> return super.onOptionsItemSelected(item) } return true } override fun onSaveInstanceState(outState: Bundle) { outState.putBoolean(MENU_VISIBLE, reader_menu.visibility == View.VISIBLE) super.onSaveInstanceState(outState) } override fun onBackPressed() { presenter.onChapterLeft() val chapterToUpdate = presenter.getMangaSyncChapterToUpdate() if (chapterToUpdate > 0) { if (presenter.prefs.askUpdateMangaSync()) { MaterialDialog.Builder(this) .content(getString(R.string.confirm_update_manga_sync, chapterToUpdate)) .positiveText(android.R.string.yes) .negativeText(android.R.string.no) .onPositive { dialog, which -> presenter.updateMangaSyncLastChapterRead() } .onAny { dialog1, which1 -> super.onBackPressed() } .show() } else { presenter.updateMangaSyncLastChapterRead() super.onBackPressed() } } else { super.onBackPressed() } } override fun onWindowFocusChanged(hasFocus: Boolean) { super.onWindowFocusChanged(hasFocus) if (hasFocus) { setSystemUiVisibility() } } override fun dispatchKeyEvent(event: KeyEvent): Boolean { if (!isFinishing) { when (event.keyCode) { KeyEvent.KEYCODE_VOLUME_DOWN -> { if (volumeKeysEnabled) { if (event.action == KeyEvent.ACTION_UP) { viewer?.moveToNext() } return true } } KeyEvent.KEYCODE_VOLUME_UP -> { if (volumeKeysEnabled) { if (event.action == KeyEvent.ACTION_UP) { viewer?.moveToPrevious() } return true } } KeyEvent.KEYCODE_DPAD_RIGHT -> { if (event.action == KeyEvent.ACTION_UP) { viewer?.moveToNext() } } KeyEvent.KEYCODE_DPAD_LEFT -> { if (event.action == KeyEvent.ACTION_UP) { viewer?.moveToPrevious() } } } } return super.dispatchKeyEvent(event) } fun onChapterError(error: Throwable) { Timber.e(error, error.message) finish() toast(R.string.page_list_error) } fun onChapterAppendError() { // Ignore } fun onChapterReady(manga: Manga, chapter: Chapter, currentPage: Page?) { val activePage = currentPage ?: chapter.pages.last() if (viewer == null) { viewer = getOrCreateViewer(manga) } viewer?.onPageListReady(chapter, activePage) if (viewer is RightToLeftReader && page_seekbar.rotation != 180f) { // Invert the seekbar for the right to left reader page_seekbar.rotation = 180f } setToolbarTitle(manga.title) setActiveChapter(chapter, activePage.pageNumber) } fun onEnterChapter(chapter: Chapter, currentPage: Int) { val activePage = if (currentPage == -1) chapter.pages.lastIndex else currentPage presenter.setActiveChapter(chapter) setActiveChapter(chapter, activePage) } fun setActiveChapter(chapter: Chapter, currentPage: Int) { val numPages = chapter.pages.size if (page_seekbar.rotation != 180f) { right_page_text.text = "$numPages" left_page_text.text = "${currentPage + 1}" } else { left_page_text.text = "$numPages" right_page_text.text = "${currentPage + 1}" } page_seekbar.max = numPages - 1 page_seekbar.progress = currentPage setToolbarSubtitle(if (chapter.chapter_number != -1f) getString(R.string.chapter_subtitle, decimalFormat.format(chapter.chapter_number.toDouble())) else chapter.name) } fun onAppendChapter(chapter: Chapter) { viewer?.onPageListAppendReady(chapter) } @Suppress("UNUSED_PARAMETER") fun onAdjacentChapters(previous: Chapter?, next: Chapter?) { setAdjacentChaptersVisibility() } private fun setAdjacentChaptersVisibility() { prevChapterBtn?.isVisible = presenter.hasPreviousChapter() nextChapterBtn?.isVisible = presenter.hasNextChapter() } private fun getOrCreateViewer(manga: Manga): BaseReader { val mangaViewer = if (manga.viewer == 0) preferences.defaultViewer() else manga.viewer // Try to reuse the viewer using its tag var fragment: BaseReader? = supportFragmentManager.findFragmentByTag(manga.viewer.toString()) as? BaseReader if (fragment == null) { // Create a new viewer when (mangaViewer) { RIGHT_TO_LEFT -> fragment = RightToLeftReader() VERTICAL -> fragment = VerticalReader() WEBTOON -> fragment = WebtoonReader() else -> fragment = LeftToRightReader() } supportFragmentManager.beginTransaction().replace(R.id.reader, fragment, manga.viewer.toString()).commit() } return fragment } fun onPageChanged(currentPageIndex: Int, totalPages: Int) { val page = currentPageIndex + 1 page_number.text = "$page/$totalPages" if (page_seekbar.rotation != 180f) { left_page_text.text = "$page" } else { right_page_text.text = "$page" } page_seekbar.progress = currentPageIndex } fun gotoPageInCurrentChapter(pageIndex: Int) { viewer?.let { val requestedPage = it.getActivePage().chapter.pages[pageIndex] it.setActivePage(requestedPage) } } fun onCenterSingleTap() { setMenuVisibility(reader_menu.visibility == View.GONE) } fun requestNextChapter() { if (!presenter.loadNextChapter()) { toast(R.string.no_next_chapter) } } fun requestPreviousChapter() { if (!presenter.loadPreviousChapter()) { toast(R.string.no_previous_chapter) } } private fun setMenuVisibility(visible: Boolean, animate: Boolean = true) { if (visible) { reader_menu.visibility = View.VISIBLE if (animate) { val toolbarAnimation = AnimationUtils.loadAnimation(this, R.anim.enter_from_top) toolbar.startAnimation(toolbarAnimation) val bottomMenuAnimation = AnimationUtils.loadAnimation(this, R.anim.enter_from_bottom) reader_menu_bottom.startAnimation(bottomMenuAnimation) } } else { val toolbarAnimation = AnimationUtils.loadAnimation(this, R.anim.exit_to_top) toolbarAnimation.setAnimationListener(object : SimpleAnimationListener() { override fun onAnimationEnd(animation: Animation) { reader_menu.visibility = View.GONE } }) toolbar.startAnimation(toolbarAnimation) val bottomMenuAnimation = AnimationUtils.loadAnimation(this, R.anim.exit_to_bottom) reader_menu_bottom.startAnimation(bottomMenuAnimation) popupMenu?.dismiss() } } private fun initializeMenu() { // Intercept all events in this layout reader_menu_bottom.setOnTouchListener { v, event -> true } page_seekbar.setOnSeekBarChangeListener(object : SimpleSeekBarListener() { override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) { if (fromUser) { gotoPageInCurrentChapter(progress) } } }) lock_orientation.setOnClickListener { v -> showImmersiveDialog(MaterialDialog.Builder(this) .title(R.string.pref_rotation_type) .items(R.array.rotation_type) .itemsCallbackSingleChoice(preferences.rotation().getOrDefault() - 1, { d, itemView, which, text -> preferences.rotation().set(which + 1) true }) .build()) } reader_zoom_selector.setOnClickListener { v -> showImmersiveDialog(MaterialDialog.Builder(this) .title(R.string.pref_zoom_start) .items(R.array.zoom_start) .itemsCallbackSingleChoice(preferences.zoomStart().getOrDefault() - 1, { d, itemView, which, text -> preferences.zoomStart().set(which + 1) true }) .build()) } reader_scale_type_selector.setOnClickListener { v -> showImmersiveDialog(MaterialDialog.Builder(this) .title(R.string.pref_image_scale_type) .items(R.array.image_scale_type) .itemsCallbackSingleChoice(preferences.imageScaleType().getOrDefault() - 1, { d, itemView, which, text -> preferences.imageScaleType().set(which + 1) true }) .build()) } reader_selector.setOnClickListener { v -> showImmersiveDialog(MaterialDialog.Builder(this) .title(R.string.pref_viewer_type) .items(R.array.viewers_selector) .itemsCallbackSingleChoice(presenter.manga.viewer, { d, itemView, which, text -> presenter.updateMangaViewer(which) recreate() true }) .build()) } val popupView = layoutInflater.inflate(R.layout.reader_popup, null) popupMenu = ReaderPopupMenu(this, popupView) reader_extra_settings.setOnClickListener { popupMenu?.let { if (!it.isShowing) it.showAtLocation(reader_extra_settings, Gravity.BOTTOM or Gravity.RIGHT, 0, reader_menu_bottom.height) else it.dismiss() } } } private fun initializeSettings() { subscriptions.add(preferences.showPageNumber().asObservable() .subscribe { setPageNumberVisibility(it) }) subscriptions.add(preferences.rotation().asObservable() .subscribe { setRotation(it) val isPortrait = resources.configuration.orientation == Configuration.ORIENTATION_PORTRAIT val resourceId = if (it == 1) R.drawable.ic_screen_rotation_white_24dp else if (isPortrait) R.drawable.ic_screen_lock_portrait_white_24dp else R.drawable.ic_screen_lock_landscape_white_24dp lock_orientation.setImageResource(resourceId) }) subscriptions.add(preferences.hideStatusBar().asObservable() .subscribe { setStatusBarVisibility(it) }) subscriptions.add(preferences.keepScreenOn().asObservable() .subscribe { setKeepScreenOn(it) }) subscriptions.add(preferences.customBrightness().asObservable() .subscribe { setCustomBrightness(it) }) subscriptions.add(preferences.readerTheme().asObservable() .distinctUntilChanged() .subscribe { applyTheme(it) }) } private fun setRotation(rotation: Int) { when (rotation) { // Rotation free 1 -> requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED // Lock in current rotation 2 -> { val currentOrientation = resources.configuration.orientation setRotation(if (currentOrientation == Configuration.ORIENTATION_PORTRAIT) 3 else 4) } // Lock in portrait 3 -> requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT // Lock in landscape 4 -> requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE } } private fun setPageNumberVisibility(visible: Boolean) { page_number.visibility = if (visible) View.VISIBLE else View.INVISIBLE } private fun setKeepScreenOn(enabled: Boolean) { if (enabled) { window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) } else { window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) } } private fun setCustomBrightness(enabled: Boolean) { if (enabled) { customBrightnessSubscription = preferences.customBrightnessValue().asObservable() .map { Math.max(0.01f, it) } .subscribe { setCustomBrightnessValue(it) } subscriptions.add(customBrightnessSubscription) } else { if (customBrightnessSubscription != null) { subscriptions.remove(customBrightnessSubscription) } setCustomBrightnessValue(WindowManager.LayoutParams.BRIGHTNESS_OVERRIDE_NONE) } } private fun setCustomBrightnessValue(value: Float) { window.attributes = window.attributes.apply { screenBrightness = value } } private fun setStatusBarVisibility(hidden: Boolean) { createUiHideFlags(hidden) setSystemUiVisibility() } private fun createUiHideFlags(statusBarHidden: Boolean) { uiFlags = 0 uiFlags = uiFlags or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION if (statusBarHidden) { uiFlags = uiFlags or View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_FULLSCREEN } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { uiFlags = uiFlags or View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY } } fun setSystemUiVisibility() { window.decorView.systemUiVisibility = uiFlags } private fun applyTheme(theme: Int) { readerTheme = theme val rootView = window.decorView.rootView if (theme == BLACK_THEME) { rootView.setBackgroundColor(Color.BLACK) page_number.setTextColor(ContextCompat.getColor(this, R.color.textColorPrimaryDark)) page_number.setBackgroundColor(ContextCompat.getColor(this, R.color.pageNumberBackgroundDark)) } else { rootView.setBackgroundColor(Color.WHITE) page_number.setTextColor(ContextCompat.getColor(this, R.color.textColorPrimaryLight)) page_number.setBackgroundColor(ContextCompat.getColor(this, R.color.pageNumberBackgroundLight)) } } private fun showImmersiveDialog(dialog: Dialog) { // Hack to not leave immersive mode dialog.window.setFlags(FLAG_NOT_FOCUSABLE, FLAG_NOT_FOCUSABLE) dialog.show() dialog.window.decorView.systemUiVisibility = window.decorView.systemUiVisibility dialog.window.clearFlags(FLAG_NOT_FOCUSABLE) } }
apache-2.0
73bb9e9f2ea3a2ca8c6007604f09999f
35.288014
118
0.603402
5.008642
false
false
false
false
ankidroid/Anki-Android
AnkiDroid/src/main/java/com/ichi2/utils/TagsUtil.kt
1
3438
/* Copyright (c) 2021 Tarek Mohamed Abdalla <[email protected]> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.ichi2.utils import java.util.stream.Collectors object TagsUtil { fun getUpdatedTags( previous: List<String>, selected: List<String>, indeterminate: List<String> ): List<String> { if (indeterminate.isEmpty()) { return selected } val updated: MutableList<String> = ArrayList() val previousSet: Set<String> = HashSet(previous) updated.addAll(selected) updated.addAll(indeterminate.stream().filter { o: String -> previousSet.contains(o) }.collect(Collectors.toList())) return updated } private const val blankSubstituent = "blank" /** * Utility method that decomposes a hierarchy tag into several parts. * Replace empty parts to "blank". */ fun getTagParts(tag: String): List<String> { val parts = tag.split("::").asSequence() return parts.map { // same as the way Anki Desktop deals with an empty tag subpart it.ifEmpty { blankSubstituent } }.toList() } /** * Utility that uniforms a hierarchy tag. * Remove trailing '::'. */ fun getUniformedTag(tag: String): String { val parts = getTagParts(tag) return if (tag.endsWith("::") && parts.last() == blankSubstituent) { parts.subList(0, parts.size - 1) } else { parts }.joinToString("::") } /** * Utility method that gets the root part of a tag. */ fun getTagRoot(tag: String): String { val parts = tag.split("::").asSequence() return parts.map { // same as the way Anki Desktop deals with an empty tag subpart it.ifEmpty { "blank" } }.take(1).first() } /** * Utility method that gets the ancestors of a tag. */ fun getTagAncestors(tag: String): List<String> { val parts = getTagParts(tag) return (0..parts.size - 2).asSequence().map { parts.subList(0, it + 1).joinToString("::") }.toList() } /** * Compare two tags with hierarchy comparison * Used to sort all tags firstly in DFN order, secondly in dictionary order * Both lhs and rhs must be uniformed. */ fun compareTag(lhs: String, rhs: String): Int { val lhsIt = lhs.split("::").asSequence().iterator() val rhsIt = rhs.split("::").asSequence().iterator() while (lhsIt.hasNext() && rhsIt.hasNext()) { val cmp = lhsIt.next().compareTo(rhsIt.next(), true) if (cmp != 0) { return cmp } } if (!lhsIt.hasNext() && !rhsIt.hasNext()) { return 0 } return if (lhsIt.hasNext()) 1 else -1 } }
gpl-3.0
88c22cda0f6f00c575ebfe71e7df9112
32.057692
123
0.605585
4.270807
false
false
false
false
EvidentSolutions/apina
apina-core/src/main/kotlin/fi/evident/apina/java/reader/ClasspathClassDataLoader.kt
1
5390
package fi.evident.apina.java.reader import fi.evident.apina.java.model.JavaClass import fi.evident.apina.utils.SkipZipPrefixStream import org.slf4j.LoggerFactory import java.io.Closeable import java.io.File import java.io.InputStream import java.util.function.Supplier import java.util.jar.JarEntry import java.util.jar.JarFile import java.util.jar.JarInputStream import java.util.zip.ZipEntry import kotlin.LazyThreadSafetyMode.SYNCHRONIZED class ClasspathClassDataLoader(classpath: Classpath) : ClassDataLoader, Closeable { private val classSuppliers = mutableMapOf<String, Supplier<JavaClass>>() private val duplicates = mutableSetOf<String>() private val resources = mutableListOf<Closeable>() init { for (root in classpath.roots) loadAllClasses(root.toFile()) } override fun close() { resources.forEach { it.close() } } override val classNames: Set<String> get() = classSuppliers.keys.toSet() val duplicateClassNames: Set<String> get() = duplicates override fun loadClass(name: String): JavaClass? = classSuppliers[name]?.get() private fun loadAllClasses(path: File) { log.debug("Scanning for classes in {}", path) when { path.isDirectory -> scanClassesUnderDirectory(path) path.isFile && path.hasExtension(".jar", ".war") -> scanClassesInArchiveFile(path) !path.exists() -> log.debug("Skipping nonexistent classpath entry: {}", path) else -> log.warn("Unknown classpath entry: $path") } } /** * When scanning top-level archives, we can easily get listing of files without * reading the whole archive. We simply read the archive directory listing and * keep pointers to the entries so we can read them lazily later on if necessary. */ private fun scanClassesInArchiveFile(path: File) { val jar = JarFile(path) resources += jar for (entry in jar.entries()) { if (entry.name.isProcessedClassFile()) { log.trace("Processing class-file {} from {}", entry.name, path) addClassSupplier(entry.name.toClassName(), JarClassDataLoader(jar, entry)) } else if (entry.isNestedArchive()) { log.trace("Processing nested library {}", entry.name) scanClassesInNestedArchive(jar.getInputStream(entry)) } } } /** * For nested archives, we can't do similar optimizations as for top-level * archives. We read class bytes into memory so we can load the classes if needed. */ private fun scanClassesInNestedArchive(stream: InputStream) { val jar = JarInputStream(SkipZipPrefixStream(stream)) while (true) { val entry = jar.nextEntry ?: break if (entry.name.isProcessedClassFile()) { log.trace("Processing class-file {} from {}", entry.name, stream) addClassSupplier(entry.name.toClassName(), LazyClassData(jar.readBytes())) } else if (entry.isNestedArchive()) { log.trace("Processing nested library {}", entry.name) scanClassesInNestedArchive(jar) } } } private fun scanClassesUnderDirectory(dir: File) { for (file in dir.walk()) { if (file.isFile && file.name.isProcessedClassFile()) { log.trace("Processing class-file {}", file) addClassSupplier(file.toRelativeString(dir).toClassName(), FileClassDataLoader(file)) } } } private fun addClassSupplier(className: String, supplier: Supplier<JavaClass>) { val old = classSuppliers.putIfAbsent(className, supplier) if (old != null) duplicates += className } private class LazyClassData(bytes: ByteArray) : Supplier<JavaClass> { private val data: JavaClass by lazy(SYNCHRONIZED) { ClassMetadataReader.loadMetadata(bytes.inputStream()) } override fun get() = data } private class JarClassDataLoader(private val jar: JarFile, private val entry: JarEntry) : Supplier<JavaClass> { private val data by lazy(SYNCHRONIZED) { ClassMetadataReader.loadMetadata(jar.getInputStream(entry)) } override fun get() = data } private class FileClassDataLoader(private val file: File) : Supplier<JavaClass> { private val data by lazy(SYNCHRONIZED) { file.inputStream().use { ClassMetadataReader.loadMetadata(it) } } override fun get() = data } companion object { private val log = LoggerFactory.getLogger(ClasspathClassDataLoader::class.java) private fun File.hasExtension(vararg extensions: String) = extensions.any { name.endsWith(it) } private fun String.toClassName() = removePrefix("WEB-INF/classes/").removePrefix("BOOT-INF/classes/").removeSuffix(".class").replace('/', '.').replace('\\', '.') private fun String.isProcessedClassFile() = endsWith(".class") && this != "module-info.class" && !startsWith("META-INF/versions") private fun ZipEntry.isNestedArchive() = name.endsWith(".jar") && (name.startsWith("lib/") || name.startsWith("WEB-INF/lib/") || name.startsWith("BOOT-INF/lib")) } }
mit
16314a3babc1a03c4aed76c558c55f3d
35.174497
138
0.641187
4.634566
false
false
false
false
FarbodSalamat-Zadeh/TimetableApp
app/src/main/java/co/timetableapp/ui/settings/SettingsActivity.kt
1
1779
/* * Copyright 2017 Farbod Salamat-Zadeh * * 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 co.timetableapp.ui.settings import android.os.Bundle import android.support.design.widget.NavigationView import android.support.v4.widget.DrawerLayout import android.support.v7.widget.Toolbar import co.timetableapp.R import co.timetableapp.ui.base.NavigationDrawerActivity /** * An activity to display a list of settings (preferences) that the user can modify. * * @see SettingsActivity */ class SettingsActivity : NavigationDrawerActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_settings) val toolbar = findViewById(R.id.toolbar) as Toolbar setSupportActionBar(toolbar) fragmentManager.beginTransaction() .replace(R.id.content, SettingsFragment()) .commit() } override fun getSelfNavDrawerItem() = NAVDRAWER_ITEM_SETTINGS override fun getSelfToolbar() = findViewById(R.id.toolbar) as Toolbar override fun getSelfDrawerLayout() = findViewById(R.id.drawerLayout) as DrawerLayout override fun getSelfNavigationView() = findViewById(R.id.navigationView) as NavigationView }
apache-2.0
fd6d63ced18289a5c62879525dee1e84
32.566038
94
0.744238
4.549872
false
false
false
false
nosix/vue-kotlin
vuekt/src/main/kotlin/org/musyozoku/vuekt/array.kt
1
2602
@file:Suppress("unused", "UnsafeCastFromDynamic", "NOTHING_TO_INLINE") // See also: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array package org.musyozoku.vuekt /** * The push() method adds one or more elements to the end of an array and returns the new length of the array. */ inline fun <T> Array<T>.push(vararg element: T): Int = this.asDynamic().push.apply(this, element) /** * The pop() method removes the last element from an array and returns that element. * This method changes the length of the array. */ inline fun <T> Array<T>.pop(): T? = this.asDynamic().pop() /** * The shift() method removes the first element from an array and returns that element. * This method changes the length of the array. */ inline fun <T> Array<T>.shift(): T? = this.asDynamic().shift() /** * The unshift() method adds one or more elements to the beginning of an array and returns the new length of the array. */ inline fun <T> Array<T>.unshift(vararg element: T): Int = this.asDynamic().unshift.apply(this, element) /** * The splice() method changes the contents of an array by removing existing elements. */ inline fun <T> Array<T>.splice(index: Int): Array<T> = this.asDynamic().splice.apply(this, arrayOf(index)) /** * The splice() method changes the contents of an array by removing existing elements. */ inline fun <T> Array<T>.splice(index: Int, howMany: Int): Array<T> = this.asDynamic().splice.apply(this, arrayOf(index, howMany)) /** * The splice() method changes the contents of an array by removing existing elements and adding new elements. */ inline fun <T> Array<T>.splice(index: Int, howMany: Int, vararg element: T): Array<T> = this.asDynamic().splice.apply(this, arrayOf(index, howMany) + element) /** * The sort() method sorts the elements of an array in place and returns the array. * The sort is not necessarily stable. * The default sort order is according to string Unicode code points. */ inline fun <T> Array<T>.sort(): Array<T> = this.asDynamic().sort() /** * The sort() method sorts the elements of an array in place and returns the array. * The sort is not necessarily stable. */ inline fun <T> Array<T>.sort(noinline compareFunction: (a: T, b: T) -> Int): Array<T> = this.asDynamic().sort(compareFunction) /** * The reverse() method reverses an array in place. * The first array element becomes the last, and the last array element becomes the first. */ inline fun <T> Array<T>.reverse(): Array<T> = this.asDynamic().reverse()
apache-2.0
7ca278f68d762c53b5f8e1ea41c9e245
35.647887
119
0.68947
3.639161
false
false
false
false
MFlisar/Lumberjack
library/src/main/java/com/michaelflisar/lumberjack/core/Level.kt
1
723
package com.michaelflisar.lumberjack.core import android.graphics.Color enum class Level( val level: Int, private val color: Int? = null, private val marker: String? = null ) { TRACE(0), DEBUG(1), INFO(2, Color.BLUE), WARN(3, Color.parseColor("#FFA500") /* orange */), ERROR(4, Color.RED), WTF(5, Color.RED, "WTF-ERROR"), UNKNOWN(-1, android.R.color.transparent) ; fun getTitleColor(textColor: Int): Int { return color ?: textColor } fun getTextColor(textColor: Int): Int { val c = getTitleColor(textColor) return if (c == android.R.color.transparent) textColor else c } fun getFileMarker() = marker ?: name }
apache-2.0
b580aecedeefdbf6fd4b22c179c3d097
21.625
54
0.608575
3.651515
false
false
false
false
petersommerhoff/kotlin
udemy-course/src/challenges/classes-challenge.kt
1
1511
package challenges /** * @author Peter Sommerhoff * * Solution for the coding challenge on classes inside the Udemy course. * Defines a Book class with the specified properties and methods. */ class Book(val title: String, val author: String, val publicationYear: Int, var borrowed: Boolean) { // You do not necessarily need to return a Boolean. fun borrow(): Boolean { if (!borrowed) { borrowed = true return true } else { println("Sorry, the book is already borrowed.") return false; } } // You do not necessarily need to return a Boolean. fun returnBook(): Boolean { if (borrowed) { borrowed = false return true } else { println("The book was not borrowed so it cannot be returned.") return false } } /** * Prints out the book to the command line including its title, author, and publication year. */ fun print() { println("Book [title=$title, author=$author, publicationYear=$publicationYear]") } } // Let's test our class. fun main(args: Array<String>) { val book = Book("The One Thing", "Gary Keller", 2013, false) book.returnBook() // Does not work because we did not borrow it yet. book.borrow() // Let's borrow it. book.borrow() // We cannot borrow again without returning. book.returnBook() // Let's return it. book.print() // And print it out. }
gpl-3.0
3200eb1b8476119d775d4b52dae35a25
29.857143
100
0.600927
4.317143
false
false
false
false
wordpress-mobile/WordPress-Stores-Android
plugins/woocommerce/src/main/kotlin/org/wordpress/android/fluxc/network/rest/wpcom/wc/order/StripOrder.kt
2
1500
package org.wordpress.android.fluxc.network.rest.wpcom.wc.order import com.google.gson.Gson import org.wordpress.android.fluxc.model.OrderEntity import org.wordpress.android.fluxc.model.order.LineItem import org.wordpress.android.fluxc.network.rest.wpcom.wc.order.OrderMappingConst.CHARGE_ID_KEY import org.wordpress.android.fluxc.network.rest.wpcom.wc.order.OrderMappingConst.SHIPPING_PHONE_KEY import org.wordpress.android.fluxc.network.rest.wpcom.wc.order.OrderMappingConst.isDisplayableAttribute import javax.inject.Inject internal class StripOrder @Inject constructor(private val gson: Gson) { operator fun invoke(fatModel: OrderEntity): OrderEntity { return fatModel.copy( lineItems = gson.toJson(fatModel.getLineItemList().map { lineItemDto: LineItem -> lineItemDto.copy( metaData = lineItemDto.metaData ?.filter { it.isDisplayableAttribute } ) }), shippingLines = gson.toJson(fatModel.getShippingLineList()), feeLines = gson.toJson(fatModel.getFeeLineList()), taxLines = gson.toJson(fatModel.getTaxLineList()), metaData = gson.toJson( fatModel.getMetaDataList() .filter { it.key == CHARGE_ID_KEY || it.key == SHIPPING_PHONE_KEY } ) ) } }
gpl-2.0
54fd120937a41cf5b143385203252341
47.387097
103
0.617333
4.518072
false
false
false
false
OpenWeen/OpenWeen.Droid
app/src/main/java/moe/tlaster/openween/view/LoginPage.kt
1
4069
package moe.tlaster.openween.view import android.graphics.Color import android.view.Gravity import android.widget.LinearLayout import com.benny.library.kbinding.dsl.OneWay import com.benny.library.kbinding.dsl.bind import com.benny.library.kbinding.view.ViewBinderComponent import devlight.io.library.ntb.NavigationTabBar import moe.tlaster.openween.R import moe.tlaster.openween.activity.LoginActivity import moe.tlaster.openween.activity.MainActivity import moe.tlaster.openween.common.extensions.ViewExtension.color import moe.tlaster.openween.common.extensions.ViewExtension.drawable import org.jetbrains.anko.* import org.jetbrains.anko.design.appBarLayout import org.jetbrains.anko.design.textInputLayout import com.benny.library.kbinding.common.bindings.* import com.benny.library.kbinding.dsl.TwoWay import com.mcxiaoke.koi.ext.onTextChange import moe.tlaster.openween.common.nameof import moe.tlaster.openween.common.textChanged import moe.tlaster.openween.viewmodel.LoginViewModel /** * Created by Tlaster on 2017/2/9. */ class LoginPage : ViewBinderComponent<LoginActivity> { override fun builder(): AnkoContext<out LoginActivity>.() -> Unit = { linearLayout { orientation = LinearLayout.VERTICAL scrollView { linearLayout { padding = dip(16) orientation = LinearLayout.VERTICAL textView("请输入以下内容完成登陆过程") textInputLayout { editText { hint = "App ID" bind { text(nameof(LoginViewModel::appId), mode = TwoWay) } bind { textChanged(nameof(LoginViewModel::onTextChanged)) } } } textInputLayout { editText { hint = "App Secret" bind { text(nameof(LoginViewModel::appSecret), mode = TwoWay) } bind { textChanged(nameof(LoginViewModel::onTextChanged)) } } } textInputLayout { editText { hint = "Redirect Uri" bind { text(nameof(LoginViewModel::redirectUri), mode = TwoWay) } bind { textChanged(nameof(LoginViewModel::onTextChanged)) } } } textInputLayout { editText { hint = "Scope" bind { text(nameof(LoginViewModel::scope), mode = TwoWay) } bind { textChanged(nameof(LoginViewModel::onTextChanged)) } } } textInputLayout { editText { hint = "Package Name" bind { text(nameof(LoginViewModel::packageName), mode = TwoWay) } bind { textChanged(nameof(LoginViewModel::onTextChanged)) } } } } }.lparams { width = matchParent height = dip(0) weight = 1f } linearLayout { orientation = LinearLayout.HORIZONTAL button("这是什么") { bind { click(nameof(LoginViewModel::what)) } }.lparams { width = dip(0) weight = 1f height = matchParent } button("下一步") { bind { click(nameof(LoginViewModel::login)) } }.lparams { width = dip(0) weight = 1f height = matchParent } }.lparams { height = dip(56) width = matchParent } } } }
mit
848ebba9dd880821e8af9a49212cb032
39.3
93
0.506081
5.588072
false
false
false
false
devmil/PaperLaunch
app/src/main/java/de/devmil/paperlaunch/view/LaunchEntryView.kt
1
8184
/* * Copyright 2015 Devmil Solutions * * 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 de.devmil.paperlaunch.view import android.content.Context import android.os.AsyncTask import android.util.AttributeSet import android.widget.ImageView import android.widget.LinearLayout import de.devmil.paperlaunch.model.IEntry import de.devmil.paperlaunch.view.utils.ViewUtils internal class LoadParams(var target: ImageView, var entry: LaunchEntryViewModel, var context: Context) internal class LoadIconTask : AsyncTask<LoadParams, Void, Void>() { override fun doInBackground(vararg params: LoadParams): Void? { for (p in params) { val icon = p.entry.appIcon p.target.post { p.target.setImageDrawable(icon) } } return null } } class LaunchEntryView : LinearLayout { private var viewModel: LaunchEntryViewModel? = null private var imgFrame: LinearLayout? = null private var appIcon: ImageView? = null private var loadTask: LoadIconTask? = null constructor(context: Context) : super(context) { construct() } constructor(context: Context, attrs: AttributeSet) : super(context, attrs) { construct() } constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr) { construct() } fun doInitialize(viewModel: LaunchEntryViewModel) { this.viewModel = viewModel adaptModelState() } val entry: IEntry get() = viewModel!!.entry fun setState(state: LaunchEntryViewModel.State) { setImageParameters(state, false, 0) } @JvmOverloads fun gotoState(state: LaunchEntryViewModel.State, delay: Int = 0) { if (viewModel?.state === state) return if (viewModel?.state?.isAnimationStateFor(state) != false) return setImageParameters(state, true, delay) } private fun construct() { ViewUtils.disableClipping(this) } private fun adaptModelState() { applyParameters() setImageParameters(viewModel!!.state, false, 0) } private fun applyParameters() { removeAllViews() val localViewModel = viewModel!! val localImgFrame = LinearLayout(context) localImgFrame.setBackgroundColor(localViewModel.frameDefaultColor) val imgFrameParams = LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT) val marginsFramePx = ViewUtils.getPxFromDip(context, localViewModel.entriesMarginDip).toInt() imgFrameParams.setMargins(marginsFramePx, marginsFramePx, marginsFramePx, marginsFramePx) addView(localImgFrame, imgFrameParams) ViewUtils.disableClipping(localImgFrame) localImgFrame.removeAllViews() val localAppIcon = ImageView(context) localAppIcon.scaleType = ImageView.ScaleType.CENTER_INSIDE val imgWidth = ViewUtils.getPxFromDip(context, localViewModel.imageWidthDip).toInt() val imgHeight = ViewUtils.getPxFromDip(context, localViewModel.imageWidthDip).toInt() val imgParams = LinearLayout.LayoutParams(imgWidth, imgHeight) val marginsImgPx = ViewUtils.getPxFromDip(context, localViewModel.imageMarginDip).toInt() imgParams.setMargins(marginsImgPx, marginsImgPx, marginsImgPx, marginsImgPx) localImgFrame.addView(localAppIcon, imgParams) ViewUtils.disableClipping(localAppIcon) loadTask?.cancel(true) val localLoadTask = LoadIconTask() localLoadTask.execute(LoadParams(localAppIcon, localViewModel, context)) localImgFrame.elevation = ViewUtils.getPxFromDip(context, localViewModel.imageElevationDip) imgFrame = localImgFrame appIcon = localAppIcon loadTask = localLoadTask } private fun getTranslateXToApply(state: LaunchEntryViewModel.State): Float { val localImgFrame = imgFrame!! val localViewModel = viewModel!! val imgWidthPx = Math.max(localImgFrame.width.toFloat(), ViewUtils.getPxFromDip(context, localViewModel.imageWidthDip)) val offset = ViewUtils.getPxFromDip(context, localViewModel.imageOffsetDip) when (state) { LaunchEntryViewModel.State.Inactive -> { return if (localViewModel.isOnRightSide) { imgWidthPx + 2 * offset } else { -(imgWidthPx + 2 * offset) } } LaunchEntryViewModel.State.Active, LaunchEntryViewModel.State.Activating -> { return if (localViewModel.isOnRightSide) { imgWidthPx / 2.0f + offset } else { -(imgWidthPx / 2.0f + offset) } } LaunchEntryViewModel.State.Focusing, LaunchEntryViewModel.State.Focused, LaunchEntryViewModel.State.Selected -> { return 0f } } } private fun getAlphaToApply(state: LaunchEntryViewModel.State): Float { return when (state) { LaunchEntryViewModel.State.Inactive, LaunchEntryViewModel.State.Active, LaunchEntryViewModel.State.Activating, LaunchEntryViewModel.State.Focusing, LaunchEntryViewModel.State.Focused -> { 1.0f } LaunchEntryViewModel.State.Selected -> { 0.0f } } } private fun setImageParameters(state: LaunchEntryViewModel.State, transit: Boolean, delay: Int) { setImageParameters(getTranslateXToApply(state), getAlphaToApply(state), transit, state, delay) } private fun setImageParameters(translateX: Float, alpha: Float, animate: Boolean, targetState: LaunchEntryViewModel.State, delay: Int) { val localImgFrame = imgFrame!! val localViewModel = viewModel!! if (!animate) { localImgFrame.translationX = translateX localImgFrame.alpha = alpha localViewModel.state = targetState } else { synchronized(this) { if (targetState.hasAnimationState()) { localViewModel.state = targetState.animationState } localImgFrame.animate() .translationX(translateX) .setDuration(localViewModel.moveDuration.toLong()) .setStartDelay(delay.toLong()) .withEndAction(object : Runnable { override fun run() { synchronized(this) { if (alpha != localImgFrame.alpha) { localImgFrame.animate() .alpha(alpha) .setDuration(localViewModel.alphaDuration.toLong()) .withEndAction { synchronized(this@LaunchEntryView) { localViewModel.state = targetState } } .start() } else { localViewModel.state = targetState } } } }) .start() } } } }
apache-2.0
c25d204acba280e7d3b01898e41d1c74
37.242991
140
0.601173
5.118199
false
false
false
false
world-federation-of-advertisers/cross-media-measurement
src/main/kotlin/org/wfanet/measurement/kingdom/deploy/gcloud/spanner/SpannerCertificatesService.kt
1
7953
// Copyright 2021 The Cross-Media Measurement 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.wfanet.measurement.kingdom.deploy.gcloud.spanner import io.grpc.Status import kotlinx.coroutines.flow.singleOrNull import org.wfanet.measurement.common.grpc.failGrpc import org.wfanet.measurement.common.grpc.grpcRequire import org.wfanet.measurement.common.grpc.grpcRequireNotNull import org.wfanet.measurement.common.identity.ExternalId import org.wfanet.measurement.common.identity.IdGenerator import org.wfanet.measurement.common.identity.InternalId import org.wfanet.measurement.gcloud.spanner.AsyncDatabaseClient import org.wfanet.measurement.internal.kingdom.Certificate import org.wfanet.measurement.internal.kingdom.CertificatesGrpcKt.CertificatesCoroutineImplBase import org.wfanet.measurement.internal.kingdom.GetCertificateRequest import org.wfanet.measurement.internal.kingdom.ReleaseCertificateHoldRequest import org.wfanet.measurement.internal.kingdom.RevokeCertificateRequest import org.wfanet.measurement.kingdom.deploy.common.DuchyIds import org.wfanet.measurement.kingdom.deploy.gcloud.spanner.common.CertSubjectKeyIdAlreadyExistsException import org.wfanet.measurement.kingdom.deploy.gcloud.spanner.common.CertificateNotFoundException import org.wfanet.measurement.kingdom.deploy.gcloud.spanner.common.CertificateRevocationStateIllegalException import org.wfanet.measurement.kingdom.deploy.gcloud.spanner.common.DataProviderNotFoundException import org.wfanet.measurement.kingdom.deploy.gcloud.spanner.common.DuchyNotFoundException import org.wfanet.measurement.kingdom.deploy.gcloud.spanner.common.KingdomInternalException import org.wfanet.measurement.kingdom.deploy.gcloud.spanner.common.MeasurementConsumerNotFoundException import org.wfanet.measurement.kingdom.deploy.gcloud.spanner.common.ModelProviderNotFoundException import org.wfanet.measurement.kingdom.deploy.gcloud.spanner.readers.BaseSpannerReader import org.wfanet.measurement.kingdom.deploy.gcloud.spanner.readers.CertificateReader import org.wfanet.measurement.kingdom.deploy.gcloud.spanner.writers.CreateCertificate import org.wfanet.measurement.kingdom.deploy.gcloud.spanner.writers.ReleaseCertificateHold import org.wfanet.measurement.kingdom.deploy.gcloud.spanner.writers.RevokeCertificate class SpannerCertificatesService( private val idGenerator: IdGenerator, private val client: AsyncDatabaseClient ) : CertificatesCoroutineImplBase() { override suspend fun createCertificate(request: Certificate): Certificate { grpcRequire(request.parentCase != Certificate.ParentCase.PARENT_NOT_SET) { "Certificate is missing parent field" } // TODO(world-federation-of-advertisers/cross-media-measurement#178) : Update fail conditions // accordingly. try { return CreateCertificate(request).execute(client, idGenerator) } catch (e: MeasurementConsumerNotFoundException) { e.throwStatusRuntimeException(Status.NOT_FOUND) { "Measurement Consumer not found." } } catch (e: DataProviderNotFoundException) { e.throwStatusRuntimeException(Status.NOT_FOUND) { "Data Provider not found." } } catch (e: ModelProviderNotFoundException) { e.throwStatusRuntimeException(Status.NOT_FOUND) { "Model Provider not found." } } catch (e: CertSubjectKeyIdAlreadyExistsException) { e.throwStatusRuntimeException(Status.ALREADY_EXISTS) { "Certificate with the subject key identifier (SKID) already exists." } } catch (e: DuchyNotFoundException) { e.throwStatusRuntimeException(Status.NOT_FOUND) { "Duchy not found." } } catch (e: KingdomInternalException) { e.throwStatusRuntimeException(Status.INTERNAL) { "Unexpected internal error" } } } override suspend fun getCertificate(request: GetCertificateRequest): Certificate { val externalCertificateId = ExternalId(request.externalCertificateId) @Suppress("WHEN_ENUM_CAN_BE_NULL_IN_JAVA") // Proto enum fields are never null. val reader: BaseSpannerReader<CertificateReader.Result> = when (request.parentCase) { GetCertificateRequest.ParentCase.EXTERNAL_DATA_PROVIDER_ID -> CertificateReader(CertificateReader.ParentType.DATA_PROVIDER) .bindWhereClause(ExternalId(request.externalDataProviderId), externalCertificateId) GetCertificateRequest.ParentCase.EXTERNAL_MEASUREMENT_CONSUMER_ID -> CertificateReader(CertificateReader.ParentType.MEASUREMENT_CONSUMER) .bindWhereClause( ExternalId(request.externalMeasurementConsumerId), externalCertificateId ) GetCertificateRequest.ParentCase.EXTERNAL_DUCHY_ID -> { val duchyId = InternalId( grpcRequireNotNull(DuchyIds.getInternalId(request.externalDuchyId)) { "Duchy with external ID ${request.externalDuchyId} not found" } ) CertificateReader(CertificateReader.ParentType.DUCHY) .bindWhereClause(duchyId, externalCertificateId) } GetCertificateRequest.ParentCase.EXTERNAL_MODEL_PROVIDER_ID -> CertificateReader(CertificateReader.ParentType.MODEL_PROVIDER) .bindWhereClause(ExternalId(request.externalModelProviderId), externalCertificateId) GetCertificateRequest.ParentCase.PARENT_NOT_SET -> throw Status.INVALID_ARGUMENT.withDescription("parent not specified").asRuntimeException() } val certificateResult = reader.execute(client.singleUse()).singleOrNull() ?: failGrpc(Status.NOT_FOUND) { "Certificate not found" } return certificateResult.certificate } override suspend fun revokeCertificate(request: RevokeCertificateRequest): Certificate { grpcRequire(request.parentCase != RevokeCertificateRequest.ParentCase.PARENT_NOT_SET) { "RevokeCertificateRequest is missing parent field" } try { return RevokeCertificate(request).execute(client, idGenerator) } catch (e: CertificateNotFoundException) { e.throwStatusRuntimeException(Status.NOT_FOUND) { "Certificate not found." } } catch (e: DuchyNotFoundException) { e.throwStatusRuntimeException(Status.NOT_FOUND) { "Duchy not found." } } catch (e: CertificateRevocationStateIllegalException) { e.throwStatusRuntimeException(Status.FAILED_PRECONDITION) { "Certificate is in wrong State." } } catch (e: KingdomInternalException) { e.throwStatusRuntimeException(Status.INTERNAL) { "Unexpected internal error" } } } override suspend fun releaseCertificateHold(request: ReleaseCertificateHoldRequest): Certificate { grpcRequire(request.parentCase != ReleaseCertificateHoldRequest.ParentCase.PARENT_NOT_SET) { "ReleaseCertificateHoldRequest is missing parent field" } try { return ReleaseCertificateHold(request).execute(client, idGenerator) } catch (e: CertificateNotFoundException) { e.throwStatusRuntimeException(Status.NOT_FOUND) { "Certificate not found." } } catch (e: DuchyNotFoundException) { e.throwStatusRuntimeException(Status.NOT_FOUND) { "Duchy not found." } } catch (e: CertificateRevocationStateIllegalException) { e.throwStatusRuntimeException(Status.FAILED_PRECONDITION) { "Certificate is in wrong State." } } catch (e: KingdomInternalException) { e.throwStatusRuntimeException(Status.INTERNAL) { "Unexpected internal error" } } } }
apache-2.0
09c971e0dc058a06ceb787bc4a342d7c
53.472603
109
0.773922
4.661782
false
false
false
false
PaulWoitaschek/Voice
app/src/main/kotlin/voice/app/uitools/VerticalChangeHandler.kt
1
1157
package voice.app.uitools import android.animation.Animator import android.animation.AnimatorSet import android.view.View import android.view.ViewGroup import com.bluelinelabs.conductor.changehandler.AnimatorChangeHandler /** * Change handler that animates vertically */ class VerticalChangeHandler : AnimatorChangeHandler() { override fun resetFromView(from: View) { } override fun getAnimator( container: ViewGroup, from: View?, to: View?, isPush: Boolean, toAddedToContainer: Boolean, ): Animator { return if (isPush && to != null) { animateFloat(to.height / 2F, 0F) { value, fraction -> to.translationY = value to.alpha = fraction }.apply { interpolator = Interpolators.fastOutSlowIn } } else if (!isPush && from != null) { animateFloat(0F, from.height / 2F) { value, fraction -> from.translationY = value from.alpha = 1 - fraction }.apply { interpolator = Interpolators.accelerate duration = from.context.resources.getInteger(android.R.integer.config_shortAnimTime).toLong() } } else { AnimatorSet() } } }
gpl-3.0
3f311a03e7d8761ccb27bffee86b5c39
26.547619
92
0.669836
4.301115
false
false
false
false
ykrank/S1-Next
library/src/main/java/com/github/ykrank/androidtools/widget/BackupDelegate.kt
1
6877
package com.github.ykrank.androidtools.widget import android.annotation.SuppressLint import android.app.Fragment import android.content.Context import android.content.Intent import androidx.annotation.IntDef import androidx.annotation.StringRes import androidx.annotation.WorkerThread import com.github.ykrank.androidtools.R import com.github.ykrank.androidtools.extension.toast import com.github.ykrank.androidtools.util.* import java.io.File import java.io.IOException /** * Created by AdminYkrank on 2016/4/21. * 设置数据库进行备份的代理 */ class BackupDelegate(private val mContext: Context, private val backupFileName: String, private val dbName: String, private val afterBackup: AfterBackup = DefaultAfterBackup(mContext), private val afterRestore: AfterRestore = DefaultAfterRestore(mContext)) { fun backup(fragment: Fragment) { val intent = FilePickerUtil.dirPickIntent(mContext) fragment.startActivityForResult(intent, BACKUP_FILE_CODE) } fun restore(fragment: Fragment) { val intent = FilePickerUtil.filePickIntent(mContext) fragment.startActivityForResult(intent, RESTORE_FILE_CODE) } fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?): Boolean { if (data == null){ return false } if (requestCode == BACKUP_FILE_CODE) { FilePickerUtil.onFilePickResult(resultCode, data, object : FilePickerUtil.OnFilePickCallback { override fun success(file: File) { RxJavaUtil.workWithUiResult({ doBackup(file) }, afterBackup::accept, this::error) } override fun cancel() { afterBackup.accept(CANCELED) } override fun error(e: Throwable) { L.e("BackupSetting:", e) } }) return true } else if (requestCode == RESTORE_FILE_CODE) { FilePickerUtil.onFilePickResult(resultCode, data, object : FilePickerUtil.OnFilePickCallback { override fun success(file: File) { RxJavaUtil.workWithUiResult({ doRestore(file) }, afterRestore::accept, this::error) } override fun cancel() { afterRestore.accept(CANCELED) } override fun error(e: Throwable) { L.e("RestoreSetting:", e) } }) return true } else { return false } } @WorkerThread @BackupResult private fun doBackup(destDir: File): Int { LooperUtil.enforceOnWorkThread() try { var dirPath = destDir.path if (destDir.isDirectory) { if (!dirPath.endsWith("/")) { dirPath += "/" } val dbFile = mContext.getDatabasePath(dbName) val destFile = File(dirPath + backupFileName) if (!destFile.exists()) { destFile.createNewFile() } FileUtil.copyFile(dbFile, destFile) return SUCCESS } else return IO_EXCEPTION } catch (e: IOException) { L.e("BackupError:", e) return if (e.message?.contains("Permission denied") == true) { PERMISSION_DENY } else IO_EXCEPTION } catch (e: Exception) { L.e("BackupError:", e) return UNKNOWN_EXCEPTION } } @WorkerThread @BackupResult private fun doRestore(srcFile: File): Int { LooperUtil.enforceOnWorkThread() try { val filePath = srcFile.path if (srcFile.isFile) { if (SQLiteUtil.isValidSQLite(filePath)) { val dbFile = mContext.getDatabasePath(dbName) FileUtil.copyFile(srcFile, dbFile) return SUCCESS } } return NO_DATA } catch (e: IOException) { L.e("RestoreError:", e) return if (e.message?.contains("Permission denied") == true) { PERMISSION_DENY } else IO_EXCEPTION } catch (e: Exception) { L.e("RestoreError:", e) return UNKNOWN_EXCEPTION } } @IntDef(SUCCESS, CANCELED, NO_DATA, PERMISSION_DENY, IO_EXCEPTION, UNKNOWN_EXCEPTION) annotation class BackupResult interface AfterBackup { fun accept(@BackupResult integer: Int?) } interface AfterRestore { fun accept(@BackupResult integer: Int?) } open class DefaultAfterBackup(val context: Context) : AfterBackup { @SuppressLint("SwitchIntDef") override fun accept(result: Int?) { @StringRes val message: Int = when (result) { BackupDelegate.SUCCESS -> R.string.message_backup_success BackupDelegate.NO_DATA -> R.string.message_no_setting_data BackupDelegate.PERMISSION_DENY -> R.string.message_permission_denied BackupDelegate.IO_EXCEPTION -> R.string.message_io_exception BackupDelegate.CANCELED -> R.string.message_operation_canceled else -> R.string.message_unknown_error } invokeMsg(message) } open fun invokeMsg(@StringRes message: Int) { context.toast(message) } } open class DefaultAfterRestore(val context: Context) : AfterRestore { @SuppressLint("SwitchIntDef") override fun accept(result: Int?) { @StringRes val message: Int = when (result) { BackupDelegate.SUCCESS -> R.string.message_restore_success BackupDelegate.NO_DATA -> R.string.message_no_setting_data BackupDelegate.PERMISSION_DENY -> R.string.message_permission_denied BackupDelegate.IO_EXCEPTION -> R.string.message_io_exception BackupDelegate.CANCELED -> R.string.message_operation_canceled else -> R.string.message_unknown_error } invokeMsg(message) } open fun invokeMsg(@StringRes message: Int) { context.toast(message) } } companion object { const val SUCCESS = 0 const val NO_DATA = 1 const val PERMISSION_DENY = 2 const val IO_EXCEPTION = 3 const val CANCELED = 4 const val UNKNOWN_EXCEPTION = 99 private val BACKUP_FILE_CODE = 11 private val RESTORE_FILE_CODE = 12 } }
apache-2.0
8947d5664e44626cf13cff7cf4a6acb3
33.437186
115
0.563549
4.987627
false
false
false
false
mopsalarm/Pr0
app/src/main/java/com/pr0gramm/app/ui/views/VoteView.kt
1
4075
package com.pr0gramm.app.ui.views import android.content.Context import android.view.View import android.widget.ImageButton import com.pr0gramm.app.R import com.pr0gramm.app.Settings import com.pr0gramm.app.orm.Vote import com.pr0gramm.app.services.ThemeHelper import com.pr0gramm.app.services.UserService import com.pr0gramm.app.ui.DrawableCache import com.pr0gramm.app.util.AndroidUtility import com.pr0gramm.app.util.di.injector import com.pr0gramm.app.util.getColorCompat class VoteViewController( private val upView: ImageButton, private val downView: ImageButton, private val activeScale: Float = 1.2f, private val inactiveScale: Float = 1f, ) { var currentVote: Vote = Vote.NEUTRAL private set private val context: Context = upView.context private val userService: UserService = context.injector.instance() // listeners for vote var onVoteClicked: ((vote: Vote) -> Boolean)? = null init { require(upView.parent === downView.parent) { "upView & downView must share the same view parent." } upView.setOnClickListener { handleVoteClicked(Vote.UP) } downView.setOnClickListener { handleVoteClicked(Vote.DOWN) } updateViewState(animate = false) } fun updateVote(vote: Vote, animate: Boolean) { if (currentVote != vote) { currentVote = vote updateViewState(animate) } } private fun handleVoteClicked(vote: Vote) { val nextVote = when (vote) { currentVote -> Vote.NEUTRAL else -> vote } if (onVoteClicked?.invoke(nextVote) == false) { // veto, do not apply vote return } updateVote(nextVote, animate = true) } private fun updateViewState(animate: Boolean) { val (upColor, downColor) = viewTintOf(currentVote) upView.setImageDrawable(DrawableCache.get(context, R.drawable.ic_vote_up, upColor)) downView.setImageDrawable(DrawableCache.get(context, R.drawable.ic_vote_down, downColor)) updateViewState( upView, animate && upView.isAttachedToWindow, scale = currentVote == Vote.UP, inactive = currentVote == Vote.DOWN, ) updateViewState( downView, animate && downView.isAttachedToWindow, scale = currentVote == Vote.DOWN, inactive = currentVote == Vote.UP, ) } private fun updateViewState(view: View, animate: Boolean, scale: Boolean, inactive: Boolean) { val targetAlpha = if (inactive) 0.25f else 1f val targetScale = if (scale) activeScale else inactiveScale val targetAngle = if (scale && Settings.rotateVoteView && userService.userIsPremium) 180f else 0f if (animate) { // no need to animate if nothing to do if (view.scaleX == targetScale && view.alpha == targetAlpha && view.rotation == targetAngle) { return } // okay, actually start animating view.animate() .scaleX(targetScale).scaleY(targetScale) .alpha(targetAlpha) .rotation(targetAngle) .setDuration(250).start() } else { // stop any animation that is still running view.animate().cancel() if (view.alpha != targetAlpha) { view.alpha = targetAlpha } view.scaleX = targetScale view.scaleY = targetScale } } private fun viewTintOf(currentVote: Vote): Pair<Int, Int> { val colorNeutral = AndroidUtility.resolveColorAttribute(context, android.R.attr.textColorSecondary) val colorUp = context.getColorCompat(ThemeHelper.accentColor) val colorDown = context.getColorCompat(R.color.white) return when (currentVote) { Vote.UP -> Pair(colorUp, colorNeutral) Vote.DOWN -> Pair(colorNeutral, colorDown) Vote.NEUTRAL -> Pair(colorNeutral, colorNeutral) } } }
mit
2a25f229a299e4a1caa4cf996a6c08f0
32.130081
107
0.631656
4.303062
false
false
false
false
SuperAwesomeLTD/sa-mobile-sdk-android
superawesome-common/src/main/java/tv/superawesome/sdk/publisher/common/components/NumberGenerator.kt
1
986
package tv.superawesome.sdk.publisher.common.components import java.util.UUID interface NumberGeneratorType { /** * @return Random percentage between 0.0 and 1.0 */ fun nextDoubleForMoat(): Double fun nextIntForCache(): Int fun nextIntForParentalGate(): Int fun nextAlphanumericString(length: Int): String } class NumberGenerator : NumberGeneratorType { private val cacheBoundMin: Int = 1000000 private val cacheBoundMax: Int = 1500000 private val parentalGateMin: Int = 50 private val parentalGateMax: Int = 99 private val moatMin: Int = 0 private val moatMax: Int = 100 override fun nextDoubleForMoat(): Double = (moatMin..moatMax).random() / 100.0 override fun nextIntForCache(): Int = (cacheBoundMin..cacheBoundMax).random() override fun nextIntForParentalGate(): Int = (parentalGateMin..parentalGateMax).random() override fun nextAlphanumericString(length: Int): String = UUID.randomUUID().toString() }
lgpl-3.0
4ab8d69b3fcfe5d08811c6948eb3176b
30.806452
92
0.726166
4.040984
false
false
false
false
SuperAwesomeLTD/sa-mobile-sdk-android
superawesome-common/src/main/java/tv/superawesome/sdk/publisher/common/ui/common/ViewableDetector.kt
1
2627
package tv.superawesome.sdk.publisher.common.ui.common import android.content.res.Resources import android.graphics.Rect import android.os.Handler import android.os.Looper import android.view.View import tv.superawesome.sdk.publisher.common.components.Logger import tv.superawesome.sdk.publisher.common.models.VoidBlock import java.lang.ref.WeakReference interface ViewableDetectorType { var isVisible: VoidBlock? fun start(view: View, targetTickCount: Int, hasBeenVisible: VoidBlock) fun cancel() } class ViewableDetector(private val logger: Logger) : ViewableDetectorType { override var isVisible: VoidBlock? = null private var viewableCounter = 0 private var runnable: Runnable? = null private var handler = Handler(Looper.getMainLooper()) override fun start(view: View, targetTickCount: Int, hasBeenVisible: VoidBlock) { logger.info("start") val weak = WeakReference(view) viewableCounter = 0 runnable = Runnable { val weakView = weak.get() ?: return@Runnable if (isViewVisible(weakView)) { logger.info("isViewVisible true") viewableCounter += 1 isVisible?.invoke() } else { logger.info("isViewVisible false") } if (viewableCounter >= targetTickCount) { logger.info("completed") hasBeenVisible() cancel() } else { logger.info("Tick: $viewableCounter") schedule() } } schedule() } private fun isViewVisible(view: View): Boolean { if (!view.isShown) { return false } val actualPosition = Rect() view.getGlobalVisibleRect(actualPosition) val screenWidth = Resources.getSystem().displayMetrics.widthPixels val screenHeight = Resources.getSystem().displayMetrics.heightPixels val screen = Rect(0, 0, screenWidth, screenHeight) return actualPosition.intersect(screen) } private fun schedule() { runnable?.let { handler.postDelayed(it, delayMillis) } } override fun cancel() { runnable?.let { handler.removeCallbacks(it) } runnable = null } } /** * Number of ticks required for banner/interstitial to decide viewable status */ const val interstitialMaxTickCount = 1 /** * Number of ticks required for video to decide viewable status */ const val videoMaxTickCount = 2 /** * The delay between each tick to check viewable status */ private const val delayMillis: Long = 1000
lgpl-3.0
9ca49740552007f7e38a982beaa8c0e5
28.852273
86
0.648268
4.625
false
false
false
false
QuickBlox/quickblox-android-sdk
sample-chat-kotlin/app/src/main/java/com/quickblox/sample/chat/kotlin/ui/activity/ForwardToActivity.kt
1
10306
package com.quickblox.sample.chat.kotlin.ui.activity import android.content.Context import android.content.Intent import android.os.Bundle import android.util.Log import android.view.Menu import android.view.MenuItem import android.view.View import android.widget.AdapterView import android.widget.LinearLayout import android.widget.ListView import android.widget.ProgressBar import com.orangegangsters.github.swipyrefreshlayout.library.SwipyRefreshLayout import com.quickblox.chat.model.QBChatDialog import com.quickblox.chat.model.QBChatMessage import com.quickblox.core.QBEntityCallback import com.quickblox.core.exception.QBResponseException import com.quickblox.core.request.QBRequestGetBuilder import com.quickblox.sample.chat.kotlin.R import com.quickblox.sample.chat.kotlin.async.BaseAsyncTask import com.quickblox.sample.chat.kotlin.managers.DialogsManager import com.quickblox.sample.chat.kotlin.ui.adapter.DialogsAdapter import com.quickblox.sample.chat.kotlin.utils.SharedPrefsHelper import com.quickblox.sample.chat.kotlin.utils.chat.ChatHelper import com.quickblox.sample.chat.kotlin.utils.qb.QbDialogHolder import com.quickblox.sample.chat.kotlin.utils.qb.QbUsersHolder import com.quickblox.sample.chat.kotlin.utils.shortToast import com.quickblox.users.model.QBUser import org.jivesoftware.smack.SmackException import java.lang.ref.WeakReference const val EXTRA_FORWARD_MESSAGE = "extra_forward_message" class ForwardToActivity : BaseActivity(), DialogsManager.ManagingDialogsCallbacks { private val TAG = ForwardToActivity::class.java.simpleName private lateinit var requestBuilder: QBRequestGetBuilder private lateinit var refreshLayout: SwipyRefreshLayout private lateinit var originMessage: QBChatMessage private lateinit var dialogsAdapter: DialogsAdapter private lateinit var currentUser: QBUser private lateinit var menu: Menu private var isProcessingResultInProgress: Boolean = false private var dialogsManager: DialogsManager = DialogsManager() private var hasMoreDialogs = true private var loadedDialogs = HashSet<QBChatDialog>() companion object { fun start(context: Context, messageToForward: QBChatMessage) { val intent = Intent(context, ForwardToActivity::class.java) intent.putExtra(EXTRA_FORWARD_MESSAGE, messageToForward) context.startActivity(intent) } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_dialogs) var progressBar = findViewById<ProgressBar>(R.id.pb_dialogs) progressBar.visibility = View.GONE if (!ChatHelper.isLogged()) { reloginToChat() } supportActionBar?.title = getString(R.string.forward_to) supportActionBar?.subtitle = getString(R.string.dialogs_actionmode_subtitle, "0") if (ChatHelper.getCurrentUser() != null) { currentUser = ChatHelper.getCurrentUser()!! } else { Log.e(TAG, "Finishing " + TAG + ". Not Logged in Chat.") finish() } originMessage = intent.getSerializableExtra(EXTRA_FORWARD_MESSAGE) as QBChatMessage requestBuilder = QBRequestGetBuilder() requestBuilder.limit = DIALOGS_PER_PAGE requestBuilder.skip = 0 initUi() } override fun onResumeFinished() { if (ChatHelper.isLogged()) { loadDialogsFromQb() } else { reloginToChat() } } private fun reloginToChat() { showProgressDialog(R.string.dlg_loading) ChatHelper.loginToChat(SharedPrefsHelper.getQbUser()!!, object : QBEntityCallback<Void> { override fun onSuccess(aVoid: Void, bundle: Bundle) { Log.d(TAG, "Relogin Successful") loadDialogsFromQb() } override fun onError(e: QBResponseException) { Log.d(TAG, "Relogin Failed " + e.message) hideProgressDialog() showErrorSnackbar(R.string.reconnect_failed, e, View.OnClickListener { reloginToChat() }) } }) } override fun onDestroy() { super.onDestroy() dialogsManager.removeManagingDialogsCallbackListener(this) } private fun initUi() { val emptyHintLayout = findViewById<LinearLayout>(R.id.ll_chat_empty) val dialogsListView: ListView = findViewById(R.id.list_dialogs_chats) refreshLayout = findViewById(R.id.swipy_refresh_layout) supportActionBar?.setDisplayHomeAsUpEnabled(true) val dialogs = ArrayList(QbDialogHolder.dialogsMap.values) dialogsAdapter = DialogsAdapter(this, dialogs) dialogsAdapter.prepareToSelect() dialogsListView.emptyView = emptyHintLayout dialogsListView.adapter = dialogsAdapter dialogsListView.onItemClickListener = AdapterView.OnItemClickListener { parent, view, position, id -> val selectedDialog = parent.getItemAtPosition(position) as QBChatDialog dialogsAdapter.toggleSelection(selectedDialog) menu.getItem(0).isVisible = (dialogsAdapter.selectedItems.size >= 1) supportActionBar?.subtitle = getString(R.string.dialogs_actionmode_subtitle, dialogsAdapter.selectedItems.size.toString()) } refreshLayout.setOnRefreshListener { loadDialogsFromQb() } refreshLayout.setColorSchemeResources(R.color.color_new_blue, R.color.random_color_2, R.color.random_color_3, R.color.random_color_7) dialogsAdapter.clearSelection() } override fun onCreateOptionsMenu(menu: Menu): Boolean { this.menu = menu menuInflater.inflate(R.menu.menu_activity_forward, menu) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { if (isProcessingResultInProgress) { return super.onOptionsItemSelected(item) } when (item.itemId) { R.id.menu_send -> { showProgressDialog(R.string.dlg_sending) ForwardedMessageSenderAsyncTask(this, dialogsAdapter.selectedItems).execute() return true } else -> return super.onOptionsItemSelected(item) } } private fun sendForwardedMessage(dialogs: ArrayList<QBChatDialog>) { for (dialog in dialogs) { try { val messageToForward = QBChatMessage() messageToForward.setSaveToHistory(true) messageToForward.dateSent = System.currentTimeMillis() / 1000 messageToForward.isMarkable = true messageToForward.attachments = originMessage.attachments if (originMessage.body == null) { messageToForward.body = null } else { messageToForward.body = originMessage.body } var senderName = "" if (originMessage.senderId == currentUser.id) { senderName = currentUser.fullName } else { val sender = QbUsersHolder.getUserById(originMessage.senderId) sender?.let { senderName = it.fullName } } messageToForward.setProperty(PROPERTY_FORWARD_USER_NAME, senderName) dialog.sendMessage(messageToForward) } catch (e: SmackException.NotConnectedException) { Log.d(TAG, "Send Forwarded Message Exception: " + e.message) shortToast(R.string.error_forwarding_not_connected) } } disableProgress() shortToast("Forwarding Complete") finish() } private fun loadDialogsFromQb() { isProcessingResultInProgress = true showProgressDialog(R.string.dlg_loading) ChatHelper.getDialogs(requestBuilder, object : QBEntityCallback<ArrayList<QBChatDialog>> { override fun onSuccess(dialogs: ArrayList<QBChatDialog>, bundle: Bundle?) { if (dialogs.size < DIALOGS_PER_PAGE) { hasMoreDialogs = false } loadedDialogs.addAll(dialogs) QbDialogHolder.addDialogs(dialogs) updateDialogsAdapter() requestBuilder.skip = loadedDialogs.size if (hasMoreDialogs) { loadDialogsFromQb() } disableProgress() } override fun onError(e: QBResponseException) { disableProgress() dialogsAdapter.clearSelection() shortToast(e.message) } }) } private fun disableProgress() { isProcessingResultInProgress = false hideProgressDialog() refreshLayout.isRefreshing = false } private fun updateDialogsAdapter() { val listDialogs = ArrayList(QbDialogHolder.dialogsMap.values) dialogsAdapter.updateList(listDialogs) dialogsAdapter.prepareToSelect() } override fun onDialogCreated(chatDialog: QBChatDialog) { loadDialogsFromQb() } override fun onDialogUpdated(chatDialog: String) { updateDialogsAdapter() } override fun onNewDialogLoaded(chatDialog: QBChatDialog) { updateDialogsAdapter() } private class ForwardedMessageSenderAsyncTask internal constructor(forwardToActivity: ForwardToActivity, private val dialogs: ArrayList<QBChatDialog>) : BaseAsyncTask<Void, Void, Void>() { private val activityRef: WeakReference<ForwardToActivity> = WeakReference(forwardToActivity) @Throws(Exception::class) override fun performInBackground(vararg params: Void): Void? { ChatHelper.join(dialogs) return null } override fun onResult(result: Void?) { activityRef.get()?.sendForwardedMessage(dialogs) } override fun onException(e: Exception) { super.onException(e) Log.d("Dialog Joiner Task", "Error: $e") shortToast("Error: " + e.message) } } }
bsd-3-clause
eb63a830b31f28c9ea8d4e1002ba61ab
37.174074
154
0.655832
5.010209
false
false
false
false
arturbosch/detekt
detekt-rules-style/src/main/kotlin/io/gitlab/arturbosch/detekt/rules/style/UnnecessaryAbstractClass.kt
1
5420
package io.gitlab.arturbosch.detekt.rules.style import io.gitlab.arturbosch.detekt.api.AnnotationExcluder import io.gitlab.arturbosch.detekt.api.CodeSmell import io.gitlab.arturbosch.detekt.api.Config import io.gitlab.arturbosch.detekt.api.Debt import io.gitlab.arturbosch.detekt.api.Entity import io.gitlab.arturbosch.detekt.api.Finding import io.gitlab.arturbosch.detekt.api.Issue import io.gitlab.arturbosch.detekt.api.Rule import io.gitlab.arturbosch.detekt.api.Severity import io.gitlab.arturbosch.detekt.api.config import io.gitlab.arturbosch.detekt.api.internal.ActiveByDefault import io.gitlab.arturbosch.detekt.api.internal.Configuration import io.gitlab.arturbosch.detekt.rules.isAbstract import io.gitlab.arturbosch.detekt.rules.isInternal import io.gitlab.arturbosch.detekt.rules.isProtected import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.descriptors.MemberDescriptor import org.jetbrains.kotlin.descriptors.Modality import org.jetbrains.kotlin.psi.KtClass import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.psi.KtNamedDeclaration import org.jetbrains.kotlin.psi.psiUtil.isAbstract import org.jetbrains.kotlin.resolve.BindingContext /** * This rule inspects `abstract` classes. In case an `abstract class` does not have any concrete members it should be * refactored into an interface. Abstract classes which do not define any `abstract` members should instead be * refactored into concrete classes. * * <noncompliant> * abstract class OnlyAbstractMembersInAbstractClass { // violation: no concrete members * * abstract val i: Int * abstract fun f() * } * * abstract class OnlyConcreteMembersInAbstractClass { // violation: no abstract members * * val i: Int = 0 * fun f() { } * } * </noncompliant> */ @ActiveByDefault(since = "1.2.0") class UnnecessaryAbstractClass(config: Config = Config.empty) : Rule(config) { private val noConcreteMember = "An abstract class without a concrete member can be refactored to an interface." private val noAbstractMember = "An abstract class without an abstract member can be refactored to a concrete class." override val issue = Issue( "UnnecessaryAbstractClass", Severity.Style, "An abstract class is unnecessary and can be refactored. " + "An abstract class should have both abstract and concrete properties or functions. " + noConcreteMember + " " + noAbstractMember, Debt.FIVE_MINS ) @Configuration("Allows you to provide a list of annotations that disable this check.") @Deprecated("Use `ignoreAnnotated` instead") private val excludeAnnotatedClasses: List<String> by config(emptyList<String>()) { classes -> classes.map { it.removePrefix("*").removeSuffix("*") } } private lateinit var annotationExcluder: AnnotationExcluder override fun visitKtFile(file: KtFile) { annotationExcluder = AnnotationExcluder(file, @Suppress("DEPRECATION") excludeAnnotatedClasses) super.visitKtFile(file) } override fun visitClass(klass: KtClass) { if (!klass.isInterface() && klass.isAbstract()) { val body = klass.body if (body != null) { val namedMembers = body.children.filterIsInstance<KtNamedDeclaration>() val namedClassMembers = NamedClassMembers(klass, namedMembers) namedClassMembers.detectAbstractAndConcreteType() } else if (klass.superTypeListEntries.isEmpty() && klass.hasConstructorParameter()) { report(CodeSmell(issue, Entity.from(klass), noAbstractMember), klass) } } super.visitClass(klass) } private fun report(finding: Finding, klass: KtClass) { if (!annotationExcluder.shouldExclude(klass.annotationEntries)) { report(finding) } } private fun KtClass.hasConstructorParameter() = primaryConstructor?.valueParameters?.isNotEmpty() == true private inner class NamedClassMembers(val klass: KtClass, val members: List<KtNamedDeclaration>) { fun detectAbstractAndConcreteType() { val (abstractMembers, concreteMembers) = members.partition { it.isAbstract() } if (abstractMembers.isEmpty() && !hasInheritedMember(true)) { report(CodeSmell(issue, Entity.from(klass), noAbstractMember), klass) return } if (abstractMembers.any { it.isInternal() || it.isProtected() } || klass.hasConstructorParameter()) return if (concreteMembers.isEmpty() && !hasInheritedMember(false)) { report(CodeSmell(issue, Entity.from(klass), noConcreteMember), klass) } } private fun hasInheritedMember(isAbstract: Boolean): Boolean { return when { klass.superTypeListEntries.isEmpty() -> false bindingContext == BindingContext.EMPTY -> true else -> { val descriptor = bindingContext[BindingContext.DECLARATION_TO_DESCRIPTOR, klass] as? ClassDescriptor descriptor?.unsubstitutedMemberScope?.getContributedDescriptors().orEmpty().any { (it as? MemberDescriptor)?.modality == Modality.ABSTRACT == isAbstract } } } } } }
apache-2.0
5569a18bfc184a72cebb81ac107908f6
41.677165
120
0.691328
4.78376
false
true
false
false
fallGamlet/DnestrCinema
app/src/main/java/com/fallgamlet/dnestrcinema/domain/models/FilmSession.kt
1
233
package com.fallgamlet.dnestrcinema.domain.models data class FilmSession( val room: String = "", val times: String = "" ) { fun isEmpty() = this == EMPTY companion object { val EMPTY = FilmSession() } }
gpl-3.0
11ca51bb0a9c95db9b326e6f3b1a4a78
18.416667
49
0.618026
4.017241
false
false
false
false
soniccat/android-taskmanager
app_wordteacher/src/main/java/com/aglushkov/wordteacher/apiproviders/wordnik/model/WordnikWord.kt
1
2899
package com.aglushkov.wordteacher.apiproviders.wordnik.model import com.google.gson.annotations.SerializedName import kotlinx.android.parcel.Parcelize import android.os.Parcelable import com.aglushkov.wordteacher.model.WordTeacherDefinition import com.aglushkov.wordteacher.model.WordTeacherWord import com.aglushkov.wordteacher.model.fromString // TODO: check possible values of WordnikLinkRelatedWords.relationshipType @Parcelize data class WordnikWord( @SerializedName("id") val id: String?, @SerializedName("attributionText") val attributionText: String?, @SerializedName("attributionUrl") val attributionUrl: String?, @SerializedName("citations") val citations: List<WordnikCitation>, @SerializedName("exampleUses") val exampleUses: List<WordnikExampleUse>, @SerializedName("labels") val labels: List<WordnikLabel>, // @SerializedName("notes") val notes: List<Any>, @SerializedName("partOfSpeech") val partOfSpeech: String?, @SerializedName("relatedWords") val relatedWords: List<WordnikRelatedWords>, @SerializedName("sourceDictionary") val sourceDictionary: String?, @SerializedName("text") val text: String?, // @SerializedName("textProns") val textProns: List<Any>, @SerializedName("word") val word: String?, @SerializedName("wordnikUrl") val wordnikUrl: String? ) : Parcelable { fun exampleUsesTexts() = exampleUses.mapNotNull { it.text } + (citations.mapNotNull { it.cite }) fun synonyms() = relatedWords.filter { it.relationshipType == "synonym" }.map { it.words }.flatten() fun related() = relatedWords.filter { it.relationshipType != "synonym" }.map { it.words }.flatten() } fun List<WordnikWord>.asWordTeacherWords(): List<WordTeacherWord> { val map: MutableMap<String, WordTeacherWord> = mutableMapOf() for (word in this) { if (word.word == null) continue val partOfSpeech = WordTeacherWord.PartOfSpeech.fromString(word.partOfSpeech) val definition = word.asDefinition() ?: continue val wordTeacherWord = map[word.word] ?: run { val word = WordTeacherWord(word.word, null, mutableMapOf(partOfSpeech to mutableListOf()), mutableListOf()) map[word.word] = word word } (wordTeacherWord.originalSources as MutableList).add(word) val definitionsMap = wordTeacherWord.definitions as MutableMap val definitionsList = definitionsMap[partOfSpeech] as MutableList definitionsList.add(definition) } return map.values.toList() } fun WordnikWord.asDefinition(): WordTeacherDefinition? { if (text == null) return null return WordTeacherDefinition( text, exampleUsesTexts(), synonyms(), null, listOf(this) ) }
mit
2f4e3775d465161ef7d744305a283411
39.84507
104
0.685064
4.515576
false
false
false
false
rsiebert/TVHClient
data/src/main/java/org/tvheadend/data/source/InputDataSource.kt
1
1398
package org.tvheadend.data.source import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import org.tvheadend.data.db.AppRoomDatabase import org.tvheadend.data.entity.Input class InputDataSource(@Suppress("unused") private val db: AppRoomDatabase) : DataSourceInterface<Input> { private var inputs: MutableList<Input> = ArrayList() override fun getLiveDataItemCount(): LiveData<Int> { val inputLiveDataCount = MutableLiveData<Int>() inputLiveDataCount.value = inputs.size return inputLiveDataCount } override fun getLiveDataItems(): LiveData<List<Input>> { val inputLiveData = MutableLiveData<List<Input>>() inputLiveData.value = getItems() return inputLiveData } override fun getLiveDataItemById(id: Any): LiveData<Input> { val inputLiveData = MutableLiveData<Input>() inputLiveData.value = getItemById(id) return inputLiveData } override fun getItems(): List<Input> { return inputs } override fun getItemById(id: Any): Input { return inputs[id as Int] } override fun addItem(item: Input) { inputs.add(item) } override fun updateItem(item: Input) { inputs.add(item) } override fun removeItem(item: Input) { inputs.remove(item) } fun removeItems() { inputs.clear() } }
gpl-3.0
9e30d286202fcc95a0a27f6c12be8bc8
25.396226
105
0.67382
4.524272
false
false
false
false
rsiebert/TVHClient
app/src/main/java/org/tvheadend/tvhclient/service/ServerTicketReceiver.kt
1
985
package org.tvheadend.tvhclient.service import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import java.lang.ref.WeakReference class ServerTicketReceiver(callback: Listener) : BroadcastReceiver() { private val callback: WeakReference<Listener> = WeakReference(callback) /** * This receiver handles the data that was given from an intent via the LocalBroadcastManager. * The main message is sent via the "message" extra. Any details about the state is given * via the "details" extra. */ override fun onReceive(context: Context, intent: Intent) { if (callback.get() != null) { (callback.get() as Listener).onServerTicketReceived(intent) } } interface Listener { fun onServerTicketReceived(intent: Intent) } companion object { const val ACTION = "server_ticket" const val PATH = "path" const val TICKET = "ticket" } }
gpl-3.0
77d32e75a1fa2f6ab0398a4dd472391b
28.848485
98
0.68934
4.560185
false
false
false
false
nextcloud/android
app/src/main/java/com/nextcloud/client/etm/EtmMenuFragment.kt
1
1913
/* * Nextcloud Android client application * * @author Chris Narkiewicz * Copyright (C) 2019 Chris Narkiewicz <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.nextcloud.client.etm import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.owncloud.android.R class EtmMenuFragment : EtmBaseFragment() { private lateinit var adapter: EtmMenuAdapter private lateinit var list: RecyclerView override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { adapter = EtmMenuAdapter(requireContext(), this::onClickedItem) adapter.pages = vm.pages val view = inflater.inflate(R.layout.fragment_etm_menu, container, false) list = view.findViewById(R.id.etm_menu_list) list.layoutManager = LinearLayoutManager(requireContext()) list.adapter = adapter return view } override fun onResume() { super.onResume() activity?.setTitle(R.string.etm_title) } private fun onClickedItem(position: Int) { vm.onPageSelected(position) } }
gpl-2.0
26b11c5b34911c0c18fc6a6c47d69d85
35.09434
116
0.738108
4.49061
false
false
false
false
is00hcw/anko
dsl/src/org/jetbrains/android/anko/config/Props.kt
3
2290
/* * Copyright 2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.android.anko.config import java.io.File import java.util.* class Variable(val name: String, val type: String) { override fun toString(): String { return "$name:$type" } } object Props { val imports: Map<String, String> by lazy { val map = hashMapOf<String, String>() File("dsl/props") .listFiles { it.name.startsWith("imports_") && it.name.endsWith(".txt") } ?.forEach { val name = it.name.replace(".txt", "") map.put(name.substring(name.indexOf('_') + 1), it.readText()) } map } val helperConstructors: Map<String, List<List<Variable>>> by lazy { val res = HashMap<String, ArrayList<List<Variable>>>() val lines = File("dsl/props/helper_constructors.txt").readLines() for (line in lines.filter { it.isNotEmpty() && !it.startsWith('#') }) { try { val separator = line.indexOf(' ') val className = line.substring(0, separator) val props = line.substring(separator + 1).split(',').map { val nameType = it.split(":".toRegex()).toTypedArray() Variable(nameType[0].trim(), nameType[1].trim()) }.toList() val constructors = res.getOrElse(className, { ArrayList<List<Variable>>() }) constructors.add(props) res.put(className, constructors) } catch (e: ArrayIndexOutOfBoundsException) { throw RuntimeException("Failed to tokenize string, malformed helper_constructors.txt") } } res } }
apache-2.0
5aef6f548409a831251867b7b2481340
35.951613
102
0.59738
4.420849
false
false
false
false
soywiz/korge
korge-spine/src/commonMain/kotlin/com/esotericsoftware/spine/Event.kt
1
2566
/****************************************************************************** * Spine Runtimes License Agreement * Last updated January 1, 2020. Replaces all prior versions. * * Copyright (c) 2013-2020, Esoteric Software LLC * * Integration of the Spine Runtimes into software or otherwise creating * derivative works of the Spine Runtimes is permitted under the terms and * conditions of Section 2 of the Spine Editor License Agreement: * http://esotericsoftware.com/spine-editor-license * * Otherwise, it is permitted to integrate the Spine Runtimes into software * or otherwise create derivative works of the Spine Runtimes (collectively, * "Products"), provided that each user of the Products must obtain their own * Spine Editor license and redistribution of the Products in any form must * include this license and copyright notice. * * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.esotericsoftware.spine import com.esotericsoftware.spine.Animation.Timeline import com.esotericsoftware.spine.AnimationState.AnimationStateListener /** Stores the current pose values for an [Event]. * * * See Timeline * [Timeline.apply], * AnimationStateListener [AnimationStateListener.event], and * [Events](http://esotericsoftware.com/spine-events) in the Spine User Guide. */ class Event( /** The animation time this event was keyed. */ val time: Float, /** The events's setup pose data. */ val data: EventData ) { var int: Int = 0 var float: Float = 0.toFloat() internal lateinit var stringValue: String var volume: Float = 0.toFloat() var balance: Float = 0.toFloat() var string: String get() = stringValue set(stringValue) { this.stringValue = stringValue } override fun toString(): String { return data.name } }
apache-2.0
35a26519d96c709d005b3df330790b4f
39.730159
82
0.712783
4.623423
false
false
false
false
MimiReader/mimi-reader
mimi-app/src/main/java/com/emogoth/android/phone/mimi/db/models/History.kt
1
2748
package com.emogoth.android.phone.mimi.db.models import androidx.annotation.NonNull import androidx.room.* import com.emogoth.android.phone.mimi.db.MimiDatabase @Entity(tableName = MimiDatabase.HISTORY_TABLE, indices = [Index(History.ID, unique = true), Index(History.BOARD_NAME), Index(History.THREAD_ID, unique = true)]) /* @Entity(tableName = MimiDatabase.HISTORY_TABLE, indices = [Index(History.KEY_THREAD_ID, unique = true)], foreignKeys = [ForeignKey(entity = Board::class, parentColumns = [Board.KEY_ID], childColumns = [History.KEY_BOARD_ID], onUpdate = ForeignKey.NO_ACTION, onDelete = ForeignKey.NO_ACTION), ForeignKey(entity = Post::class, parentColumns = [History.KEY_ID], childColumns = [Post.KEY_HISTORY_ID], onDelete = ForeignKey.CASCADE)]) */ class History( @PrimaryKey(autoGenerate = true) @ColumnInfo(name = ID) var id: Int? = null, @ColumnInfo(name = ORDER_ID) var orderId: Int = 0, @ColumnInfo(name = THREAD_ID) var threadId: Long = 0, @ColumnInfo(name = BOARD_NAME) var boardName: String = "", @ColumnInfo(name = USER_NAME) var userName: String = "", @ColumnInfo(name = LAST_ACCESS) var lastAccess: Long = 0, @ColumnInfo(name = POST_TIM) var tim: String = "", @NonNull @ColumnInfo(name = POST_TEXT) var text: String = "", @ColumnInfo(name = WATCHED) var watched: Boolean = false, // TODO: Change to Bool @ColumnInfo(name = SIZE) var threadSize: Int = 0, @ColumnInfo(name = REPLIES) var replies: String = "", @ColumnInfo(name = THREAD_REMOVED) var removed: Boolean = false, @ColumnInfo(name = LAST_READ_POS) var lastReadPosition: Int = 0, @ColumnInfo(name = UNREAD_COUNT) var unreadCount: Int = 0 ) { companion object { const val ID = "id" const val ORDER_ID = "order_id" const val THREAD_ID = "thread_id" const val BOARD_NAME = "board_path" const val USER_NAME = "user_name" const val POST_TIM = "post_tim" // thumbnail const val POST_TEXT = "post_text" // preview text const val LAST_ACCESS = "last_access" const val WATCHED = "watched" const val SIZE = "thread_size" const val REPLIES = "post_replies" const val THREAD_REMOVED = "thread_removed" const val LAST_READ_POS = "last_read_position" const val UNREAD_COUNT = "unread_count" } @Ignore var comment: CharSequence? = null }
apache-2.0
2963c2b93ad670c63d5a6b0c84a36341
30.238636
121
0.584061
4.065089
false
false
false
false
pyamsoft/pasterino
app/src/main/java/com/pyamsoft/pasterino/main/ToolbarViewModel.kt
1
1453
/* * Copyright 2020 Peter Kenji Yamanaka * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.pyamsoft.pasterino.main import com.pyamsoft.pydroid.arch.UiViewModel import com.pyamsoft.pydroid.arch.UnitControllerEvent import timber.log.Timber import javax.inject.Inject internal class ToolbarViewModel @Inject internal constructor() : UiViewModel<ToolbarViewState, UnitControllerEvent>( initialState = ToolbarViewState( topBarHeight = 0, bottomSpaceHeight = 0, ), ) { internal fun handleSetTopBarHeight(height: Int) { Timber.d("Set top bar height: $height") setState { if (topBarHeight == height) this else copy(topBarHeight = height) } } internal fun handleSetBottomSpaceHeight(height: Int) { Timber.d("Set bottom space height: $height") setState { if (bottomSpaceHeight == height) this else copy(bottomSpaceHeight = height) } } }
apache-2.0
6268d2b7a355cd60eb152d8896d3ffde
33.595238
92
0.716449
4.273529
false
false
false
false
pokk/KotlinKnifer
kotlinknifer/src/main/java/com/devrapid/kotlinknifer/View.kt
1
3883
@file:Suppress("NOTHING_TO_INLINE") package com.devrapid.kotlinknifer import android.app.Activity import android.content.Context import android.graphics.Rect import android.os.Build import android.view.View import android.view.View.* import android.view.ViewTreeObserver import android.view.Window import android.view.WindowManager import androidx.annotation.ColorInt import androidx.annotation.ColorRes import androidx.appcompat.app.AlertDialog import androidx.core.content.ContextCompat inline fun View.resizeView(width: Int? = null, height: Int? = null) { val newLayoutParams = layoutParams?.apply { height?.let { this.height = it } width?.let { this.width = it } } layoutParams = newLayoutParams } inline fun View.visible() { visibility = VISIBLE } inline fun View.invisible() { visibility = INVISIBLE } inline fun View.gone() { visibility = GONE } @Deprecated("It's replaced by ktx", ReplaceWith("isVisible", "androidx.core.view.isVisible")) inline fun View.isVisible() = VISIBLE == visibility fun View.waitForMeasure(func: (v: View, w: Int, h: Int) -> Unit) { if (0 < width && 0 < height) { func(this, width, height) return } val listener = object : ViewTreeObserver.OnPreDrawListener { override fun onPreDraw(): Boolean { val observer = [email protected] if (observer.isAlive) { observer.removeOnPreDrawListener(this) } func(this@waitForMeasure, [email protected], [email protected]) observer.removeOnPreDrawListener(this) return true } } viewTreeObserver.addOnPreDrawListener(listener) } fun Context.alert(message: String, title: String? = null, init: (AlertDialog.Builder.() -> Unit)? = null) = AlertDialog.Builder(this).apply { [email protected](R.style.Base_Theme_AppCompat_Dialog_Alert) title?.let { setTitle(title) } setMessage(message) init?.let { init() } } fun Context.alert(message: Int, title: Int? = null, init: (AlertDialog.Builder.() -> Unit)? = null) = AlertDialog.Builder(this).apply { [email protected](R.style.Base_Theme_AppCompat_Dialog_Alert) title?.let { setTitle(title) } setMessage(message) init?.let { init() } } inline fun Context.navigationBarHeight() = getIdentifier("navigation_bar_height", "dimen", "android") .takeIf { 0 < it } ?.let { getDimenPixelSize(it) } ?: 0 inline fun Context.statusBarHeight() = getIdentifier("status_bar_height", "dimen", "android") .takeIf { 0 < it } ?.let { getDimenPixelSize(it) } ?: 0 inline fun Activity.statusBarHeight() = Rect() .apply { window.decorView.getWindowVisibleDisplayFrame(this) } .top fun Activity.changeStatusBarColorRes(@ColorRes colorRes: Int) = setStatusBarColorBy { statusBarColor = ContextCompat.getColor(context, colorRes) } fun Activity.changeStatusBarColor(@ColorInt color: Int, ratio: Float = 1f) = setStatusBarColorBy { statusBarColor = color.ofAlpha(ratio) } internal inline fun Activity.setStatusBarColorBy(block: Window.() -> Unit) { if (Build.VERSION_CODES.LOLLIPOP <= Build.VERSION.SDK_INT) { window.apply { clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS) addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS) block() // For not opaque(transparent) color. decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN } } else { TODO("Don't support the sdk version is less than 21 yet.") } }
apache-2.0
7b8304ea144192058ec5d767f24272d9
33.362832
117
0.653361
4.290608
false
false
false
false
mctoyama/PixelClient
src/main/kotlin/org/pixelndice/table/pixelclient/fx/BoardRemarkPoint.kt
1
1573
package org.pixelndice.table.pixelclient.fx import javafx.scene.canvas.GraphicsContext import javafx.scene.paint.Color import javafx.scene.shape.ArcType import org.pixelndice.table.pixelclient.misc.Point class BoardRemarkPoint(private val location: Point){ private val startMillis: Long = System.currentTimeMillis() val endMillis: Long private val maxRadius = PixelCanvas.GRID_WIDTH * 3.0 private val speedRadius: Double private var radius: Double = 0.0 get(){ field = (System.currentTimeMillis() - startMillis) * speedRadius return field } init { endMillis = startMillis + 5000L speedRadius = maxRadius / (endMillis- startMillis) } fun draw(gc: GraphicsContext){ val tmpRadius = radius gc.save() gc.fill = Color.RED gc.lineWidth = 2.0 gc.strokeArc(location.x-(tmpRadius/2.0), location.y-(tmpRadius/2.0), tmpRadius, tmpRadius, 0.0, 360.0, ArcType.CHORD) gc.restore() } companion object { var isClicked = false set(value){ if( value ) clickedTime = System.currentTimeMillis() field = value } private var clickedTime: Long = 0L private const val DELTA = 1000L fun get(point: Point): BoardRemarkPoint? { if( isClicked && clickedTime + DELTA < System.currentTimeMillis() ) { isClicked = false return BoardRemarkPoint(point) } return null } } }
bsd-2-clause
4bd11368bfa3093db8a54bca0c131227
22.833333
125
0.607756
4.393855
false
false
false
false
wikimedia/apps-android-wikipedia
app/src/main/java/org/wikipedia/talk/TalkTopicsViewModel.kt
1
11894
package org.wikipedia.talk import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.viewModelScope import kotlinx.coroutines.* import kotlinx.coroutines.flow.MutableStateFlow import org.wikipedia.analytics.WatchlistFunnel import org.wikipedia.csrf.CsrfTokenClient import org.wikipedia.database.AppDatabase import org.wikipedia.dataclient.ServiceFactory import org.wikipedia.dataclient.discussiontools.ThreadItem import org.wikipedia.dataclient.mwapi.MwQueryPage import org.wikipedia.edit.Edit import org.wikipedia.page.Namespace import org.wikipedia.page.PageTitle import org.wikipedia.richtext.RichTextUtil import org.wikipedia.settings.Prefs import org.wikipedia.staticdata.TalkAliasData import org.wikipedia.staticdata.UserTalkAliasData import org.wikipedia.talk.db.TalkPageSeen import org.wikipedia.util.log.L import org.wikipedia.views.TalkTopicsSortOverflowView import org.wikipedia.watchlist.WatchlistExpiry class TalkTopicsViewModel(var pageTitle: PageTitle, private val sidePanel: Boolean) : ViewModel() { private val talkPageDao = AppDatabase.instance.talkPageSeenDao() private val handler = CoroutineExceptionHandler { _, throwable -> uiState.value = UiState.LoadError(throwable) } private val editHandler = CoroutineExceptionHandler { _, throwable -> uiState.value = UiState.EditError(throwable) } private val watchlistFunnel = WatchlistFunnel() val threadItems = mutableListOf<ThreadItem>() var sortedThreadItems = listOf<ThreadItem>() var lastRevision: MwQueryPage.Revision? = null var watchlistExpiryChanged = false var isWatched = false var hasWatchlistExpiry = false var lastWatchExpiry = WatchlistExpiry.NEVER var currentSearchQuery: String? = null set(value) { field = value sortAndFilterThreadItems() } var currentSortMode = Prefs.talkTopicsSortMode set(value) { field = value Prefs.talkTopicsSortMode = field sortAndFilterThreadItems() } val uiState = MutableStateFlow(UiState()) init { loadTopics() } fun loadTopics() { // Determine whether we need to resolve the PageTitle, since the calling activity might // have given us a non-Talk page, and we need to prepend the correct namespace. var resolveTitleRequired = false if (pageTitle.namespace.isEmpty()) { pageTitle.namespace = TalkAliasData.valueFor(pageTitle.wikiSite.languageCode) } else if (pageTitle.isUserPage) { pageTitle.namespace = UserTalkAliasData.valueFor(pageTitle.wikiSite.languageCode) } else if (pageTitle.namespace() != Namespace.TALK && pageTitle.namespace() != Namespace.USER_TALK) { // defer resolution of Talk page title for an API call. resolveTitleRequired = true } uiState.value = UiState.UpdateNamespace(pageTitle) viewModelScope.launch(handler) { if (resolveTitleRequired) { val siteInfoResponse = withContext(Dispatchers.IO) { ServiceFactory.get(pageTitle.wikiSite).getPageNamespaceWithSiteInfo(pageTitle.prefixedText) } resolveTitleRequired = false siteInfoResponse.query?.namespaces?.let { namespaces -> siteInfoResponse.query?.firstPage()?.let { page -> // In MediaWiki, namespaces that are even-numbered are "regular" pages, // and namespaces that are odd-numbered are the "Talk" versions of the // corresponding even-numbered namespace. For example, "User"=2, "User talk"=3. // So then, if the namespace of our pageTitle is even (i.e. not a Talk page), // then increment the namespace by 1, and update the pageTitle with it. val newNs = namespaces.values.find { it.id == page.namespace().code() + 1 } if (page.namespace().code() % 2 == 0 && newNs != null) { pageTitle.namespace = newNs.name } } } } val discussionToolsInfoResponse = async { ServiceFactory.get(pageTitle.wikiSite).getTalkPageTopics(pageTitle.prefixedText) } val lastModifiedResponse = async { ServiceFactory.get(pageTitle.wikiSite).getLastModified(pageTitle.prefixedText) } val watchStatus = withContext(Dispatchers.Default) { if (!sidePanel) ServiceFactory.get(pageTitle.wikiSite) .getWatchedStatus(pageTitle.prefixedText).query?.firstPage()!! else MwQueryPage() } threadItems.clear() threadItems.addAll(discussionToolsInfoResponse.await().pageInfo?.threads ?: emptyList()) lastRevision = lastModifiedResponse.await().query?.firstPage()?.revisions?.firstOrNull() sortAndFilterThreadItems() isWatched = watchStatus.watched hasWatchlistExpiry = watchStatus.hasWatchlistExpiry() uiState.value = UiState.LoadTopic(pageTitle, threadItems) } } fun updatePageTitle(pageTitle: PageTitle) { this.pageTitle = pageTitle.copy() loadTopics() } fun undoSave(newRevisionId: Long, undoneSubject: CharSequence, undoneBody: CharSequence) { viewModelScope.launch(editHandler) { val token = withContext(Dispatchers.IO) { CsrfTokenClient.getToken(pageTitle.wikiSite).blockingFirst() } val undoResponse = ServiceFactory.get(pageTitle.wikiSite).postUndoEdit(title = pageTitle.prefixedText, undoRevId = newRevisionId, token = token) uiState.value = UiState.UndoEdit(undoResponse, undoneSubject, undoneBody) } } fun markAsSeen(threadItem: ThreadItem?, force: Boolean = false) { threadSha(threadItem)?.let { viewModelScope.launch(editHandler) { withContext(Dispatchers.Main) { if (topicSeen(threadItem) && !force) { talkPageDao.deleteTalkPageSeen(it) } else { talkPageDao.insertTalkPageSeen(TalkPageSeen(it)) } } } } } fun topicSeen(threadItem: ThreadItem?): Boolean { return threadSha(threadItem)?.run { talkPageDao.getTalkPageSeen(this) != null } ?: false } private fun threadSha(threadItem: ThreadItem?): String? { return threadItem?.let { it.id + "|" + it.allReplies.map { reply -> reply.timestamp }.maxOrNull() } } fun subscribeTopic(commentName: String, subscribed: Boolean) { viewModelScope.launch(CoroutineExceptionHandler { _, throwable -> L.e(throwable) }) { val token = withContext(Dispatchers.IO) { CsrfTokenClient.getToken(pageTitle.wikiSite).blockingFirst() } ServiceFactory.get(pageTitle.wikiSite).subscribeTalkPageTopic(pageTitle.prefixedText, commentName, token, if (!subscribed) true else null) } } private fun sortAndFilterThreadItems() { when (currentSortMode) { TalkTopicsSortOverflowView.SORT_BY_DATE_PUBLISHED_DESCENDING -> { threadItems.sortByDescending { it.replies.firstOrNull()?.date } } TalkTopicsSortOverflowView.SORT_BY_DATE_PUBLISHED_ASCENDING -> { threadItems.sortBy { it.replies.firstOrNull()?.date } } TalkTopicsSortOverflowView.SORT_BY_TOPIC_NAME_DESCENDING -> { threadItems.sortByDescending { RichTextUtil.stripHtml(it.html) } } TalkTopicsSortOverflowView.SORT_BY_TOPIC_NAME_ASCENDING -> { threadItems.sortBy { RichTextUtil.stripHtml(it.html) } } TalkTopicsSortOverflowView.SORT_BY_DATE_UPDATED_DESCENDING -> { threadItems.sortByDescending { it.replies.lastOrNull()?.date } } TalkTopicsSortOverflowView.SORT_BY_DATE_UPDATED_ASCENDING -> { threadItems.sortBy { it.replies.lastOrNull()?.date } } } // Regardless of sort order, always put header template at the top, if we have one. val headerItem = threadItems.find { it.othercontent.isNotEmpty() && TalkTopicActivity.isHeaderTemplate(it) } if (headerItem != null) { threadItems.remove(headerItem) threadItems.add(0, headerItem) } sortedThreadItems = threadItems.filter { it.plainText.contains(currentSearchQuery.orEmpty(), true) || it.plainOtherContent.contains(currentSearchQuery.orEmpty(), true) || it.allReplies.any { reply -> reply.plainText.contains(currentSearchQuery.orEmpty(), true) || reply.author.contains(currentSearchQuery.orEmpty(), true) } } } suspend fun isSubscribed(commentName: String): Boolean { val response = ServiceFactory.get(pageTitle.wikiSite).getTalkPageTopicSubscriptions(commentName) return response.subscriptions[commentName] == 1 } fun watchOrUnwatch(expiry: WatchlistExpiry, unwatch: Boolean) { viewModelScope.launch(CoroutineExceptionHandler { _, throwable -> L.e(throwable) }) { withContext(Dispatchers.IO) { if (expiry != WatchlistExpiry.NEVER) { watchlistFunnel.logAddExpiry() } else { if (isWatched) { watchlistFunnel.logRemoveArticle() } else { watchlistFunnel.logAddArticle() } } val token = ServiceFactory.get(pageTitle.wikiSite).getWatchToken().query?.watchToken() val response = ServiceFactory.get(pageTitle.wikiSite) .watch(if (unwatch) 1 else null, null, pageTitle.prefixedText, expiry.expiry, token!!) lastWatchExpiry = expiry if (watchlistExpiryChanged && unwatch) { watchlistExpiryChanged = false } if (unwatch) { watchlistFunnel.logRemoveSuccess() } else { watchlistFunnel.logAddSuccess() } response.getFirst()?.let { isWatched = it.watched hasWatchlistExpiry = lastWatchExpiry != WatchlistExpiry.NEVER // We have to send values to the object, even if we use the variables from ViewModel. // Otherwise the status will not be updated in the activity since the values in the object remains the same. uiState.value = UiState.DoWatch(isWatched, hasWatchlistExpiry) } } } } class Factory(private val pageTitle: PageTitle, private val sidePanel: Boolean = false) : ViewModelProvider.Factory { @Suppress("unchecked_cast") override fun <T : ViewModel> create(modelClass: Class<T>): T { return TalkTopicsViewModel(pageTitle.copy(), sidePanel) as T } } open class UiState { data class UpdateNamespace(val pageTitle: PageTitle) : UiState() data class LoadTopic(val pageTitle: PageTitle, val threadItems: List<ThreadItem>) : UiState() data class LoadError(val throwable: Throwable) : UiState() data class UndoEdit(val edit: Edit, val undoneSubject: CharSequence, val undoneBody: CharSequence) : UiState() data class DoWatch(val isWatched: Boolean, val hasWatchlistExpiry: Boolean) : UiState() data class EditError(val throwable: Throwable) : UiState() } }
apache-2.0
329d9a376667be705b580bcf4220bba8
45.280156
156
0.633681
4.976569
false
false
false
false
stripe/stripe-android
payments-core/src/main/java/com/stripe/android/networking/DefaultAlipayRepository.kt
1
2134
package com.stripe.android.networking import com.stripe.android.AlipayAuthenticator import com.stripe.android.StripeIntentResult import com.stripe.android.core.networking.ApiRequest import com.stripe.android.model.AlipayAuthResult import com.stripe.android.model.PaymentIntent import com.stripe.android.model.StripeIntent internal class DefaultAlipayRepository( private val stripeRepository: StripeRepository ) : AlipayRepository { override suspend fun authenticate( paymentIntent: PaymentIntent, authenticator: AlipayAuthenticator, requestOptions: ApiRequest.Options ): AlipayAuthResult { if (paymentIntent.paymentMethod?.liveMode == false) { throw IllegalArgumentException( "Attempted to authenticate test mode " + "PaymentIntent with the Alipay SDK.\n" + "The Alipay SDK does not support test mode payments." ) } val nextActionData = paymentIntent.nextActionData if (nextActionData is StripeIntent.NextActionData.AlipayRedirect) { val output = authenticator.onAuthenticationRequest(nextActionData.data) return AlipayAuthResult( when (output[ALIPAY_RESULT_FIELD]) { AlipayAuthResult.RESULT_CODE_SUCCESS -> { nextActionData.authCompleteUrl?.let { authCompleteUrl -> stripeRepository.retrieveObject(authCompleteUrl, requestOptions) } StripeIntentResult.Outcome.SUCCEEDED } AlipayAuthResult.RESULT_CODE_FAILED -> StripeIntentResult.Outcome.FAILED AlipayAuthResult.RESULT_CODE_CANCELLED -> StripeIntentResult.Outcome.CANCELED else -> StripeIntentResult.Outcome.UNKNOWN } ) } else { throw RuntimeException("Unable to authenticate Payment Intent with Alipay SDK") } } private companion object { private const val ALIPAY_RESULT_FIELD = "resultStatus" } }
mit
66c62801fd0538d504118e1daf6c9ed0
40.843137
97
0.64433
5.705882
false
false
false
false
wendigo/chrome-reactive-kotlin
src/main/kotlin/pl/wendigo/chrome/targets/Manager.kt
1
6191
package pl.wendigo.chrome.targets import org.slf4j.Logger import org.slf4j.LoggerFactory import pl.wendigo.chrome.api.ProtocolDomains import pl.wendigo.chrome.api.target.AttachToTargetRequest import pl.wendigo.chrome.api.target.CloseTargetRequest import pl.wendigo.chrome.api.target.CreateBrowserContextRequest import pl.wendigo.chrome.api.target.CreateTargetRequest import pl.wendigo.chrome.api.target.DisposeBrowserContextRequest import pl.wendigo.chrome.api.target.GetTargetInfoRequest import pl.wendigo.chrome.api.target.SetDiscoverTargetsRequest import pl.wendigo.chrome.api.target.TargetID import pl.wendigo.chrome.api.target.TargetInfo import pl.wendigo.chrome.on import pl.wendigo.chrome.protocol.ProtocolConnection import pl.wendigo.chrome.sync import java.io.Closeable /** * [Manager] is responsible for querying, creating, closing, attaching to debuggable [Target]s on the controlled Chrome instance. */ class Manager( private val browserDebuggerAddress: String, private val multiplexConnections: Boolean, private val eventsBufferSize: Int, private val domains: ProtocolDomains ) : Closeable, AutoCloseable { private val targets: MutableMap<TargetID, TargetInfo> = mutableMapOf() /** * Closes underlying connection to debugger. */ override fun close() { domains.close() } init { on(domains.Target.targetCreated().filter { it.targetInfo.isPage() }) { targets[it.targetInfo.targetId] = it.targetInfo logger.debug("Target {} was created", it.targetInfo) } on(domains.Target.targetDestroyed()) { if (targets.remove(it.targetId) != null) { logger.debug("Target {} was destroyed", it.targetId) } } on(domains.Target.targetInfoChanged().filter { it.targetInfo.isPage() }) { targets[it.targetInfo.targetId] = it.targetInfo logger.debug("Target {} was changed", it.targetInfo) } on(domains.Target.targetCrashed()) { if (targets.remove(it.targetId) != null) { logger.debug("Target {} has crashed", it.targetId) } } sync(domains.Target.setDiscoverTargets(SetDiscoverTargetsRequest(discover = true))) } /** * Closes target and destroys browser context if present on the browser side effectively releasing all resources . * * If [multiplexConnections] is false, then underlying connection to the [Target]'s debugger is also closed. */ fun close(target: Target) { logger.info("Closing {}...", target) val browserContextID = target.info().browserContextId sync(domains.Target.closeTarget(CloseTargetRequest(target.targetId()))).run { logger.info("Closed {}", target.session()) } if (!browserContextID.isNullOrEmpty()) { sync(domains.Target.disposeBrowserContext(DisposeBrowserContextRequest(browserContextID))).run { logger.info("Destroyed browser context {}", browserContextID) } } if (!multiplexConnections) { target.closeConnection() } } /** * Creates new target with given [url] and viewport [width] and [height]. * * If [incognito] is true, than new target is created in separate browser context (think of it as incognito window). */ internal fun create(url: String, incognito: Boolean = true, width: Int = 1024, height: Int = 768): Target { logger.info("Creating new target [url=$url, incognito=$incognito, viewport=[$width, $height]]") val browserContextId = when (incognito) { true -> sync(domains.Target.createBrowserContext(CreateBrowserContextRequest(disposeOnDetach = true))).browserContextId false -> null } val (targetId) = sync( domains.Target.createTarget( CreateTargetRequest( url = url, browserContextId = browserContextId, height = height, width = width, background = true ) ) ) val targetInfo = sync(domains.Target.getTargetInfo(GetTargetInfoRequest(targetId = targetId))).targetInfo logger.info("Created new target [$targetInfo]") return attach(targetInfo) } /** * Returns list of all debuggable targets on the browser side. */ fun list(): List<TargetInfo> { return targets.values.toList() } /** * Attaches to given [TargetInfo] and returns new [Target] for it. * * If [multiplexConnections] is true then existing debugger browser connection is used: [#991325](https://crbug.com/991325)) * Otherwise new underlying connection to target's debugger endpoint is established. */ fun attach(target: TargetInfo): Target { val sessionId = when (multiplexConnections) { true -> sync( domains.Target.attachToTarget( AttachToTargetRequest( targetId = target.targetId, flatten = true ) ) ).sessionId false -> "" } return Target( session = target.toTarget(sessionId), connection = openConnection(target, sessionId), manager = this ) } /** * Constructs target debugger address (if not using multiplexed connections). */ private fun targetWsAddress(targetID: TargetID): String { return browserDebuggerAddress.replace( browserDebuggerAddress.substringAfterLast("devtools"), "/page/$targetID" ) } private fun openConnection(target: TargetInfo, sessionId: String): ProtocolConnection { return when (multiplexConnections) { true -> domains.cloneConnection(sessionId) false -> ProtocolConnection.open(targetWsAddress(target.targetId), eventsBufferSize) } } companion object { private val logger: Logger = LoggerFactory.getLogger(Manager::class.java) } }
apache-2.0
0e8a30b17cacbf949c46a10af79bd6c3
34.377143
131
0.637054
4.704407
false
false
false
false
stripe/stripe-android
link/src/test/java/com/stripe/android/link/ui/wallet/WalletViewModelTest.kt
1
25098
package com.stripe.android.link.ui.wallet import androidx.lifecycle.Lifecycle import androidx.savedstate.SavedStateRegistry import androidx.savedstate.SavedStateRegistryOwner import app.cash.turbine.test import com.google.common.truth.Truth.assertThat import com.stripe.android.R import com.stripe.android.core.Logger import com.stripe.android.core.exception.APIConnectionException import com.stripe.android.core.injection.Injectable import com.stripe.android.core.injection.NonFallbackInjector import com.stripe.android.link.LinkActivityContract import com.stripe.android.link.LinkActivityResult import com.stripe.android.link.LinkActivityResult.Canceled.Reason import com.stripe.android.link.LinkScreen import com.stripe.android.link.account.LinkAccountManager import com.stripe.android.link.confirmation.ConfirmationManager import com.stripe.android.link.confirmation.PaymentConfirmationCallback import com.stripe.android.link.injection.SignedInViewModelSubcomponent import com.stripe.android.link.model.LinkAccount import com.stripe.android.link.model.Navigator import com.stripe.android.link.model.PaymentDetailsFixtures.CONSUMER_PAYMENT_DETAILS import com.stripe.android.link.model.StripeIntentFixtures import com.stripe.android.link.ui.ErrorMessage import com.stripe.android.link.ui.PrimaryButtonState import com.stripe.android.model.CardBrand import com.stripe.android.model.ConfirmPaymentIntentParams import com.stripe.android.model.ConfirmStripeIntentParams import com.stripe.android.model.ConsumerPaymentDetails import com.stripe.android.model.ConsumerPaymentDetailsUpdateParams import com.stripe.android.model.CvcCheck import com.stripe.android.model.PaymentMethodCreateParams import com.stripe.android.payments.paymentlauncher.PaymentResult import com.stripe.android.ui.core.elements.IdentifierSpec import com.stripe.android.ui.core.forms.FormFieldEntry import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.test.UnconfinedTestDispatcher import kotlinx.coroutines.test.advanceTimeBy import kotlinx.coroutines.test.resetMain import kotlinx.coroutines.test.runTest import kotlinx.coroutines.test.setMain import org.junit.After import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.mockito.kotlin.any import org.mockito.kotlin.anyOrNull import org.mockito.kotlin.argWhere import org.mockito.kotlin.argumentCaptor import org.mockito.kotlin.clearInvocations import org.mockito.kotlin.eq import org.mockito.kotlin.mock import org.mockito.kotlin.never import org.mockito.kotlin.spy import org.mockito.kotlin.verify import org.mockito.kotlin.whenever import org.robolectric.RobolectricTestRunner import java.util.Calendar import javax.inject.Provider import kotlin.random.Random @ExperimentalCoroutinesApi @RunWith(RobolectricTestRunner::class) class WalletViewModelTest { private val args = mock<LinkActivityContract.Args>() private lateinit var linkAccountManager: LinkAccountManager private val navigator = mock<Navigator>() private val confirmationManager = mock<ConfirmationManager>() private val logger = Logger.noop() @Before fun before() { Dispatchers.setMain(UnconfinedTestDispatcher()) whenever(args.stripeIntent).thenReturn(StripeIntentFixtures.PI_SUCCEEDED) val mockLinkAccount = mock<LinkAccount>().apply { whenever(clientSecret).thenReturn(CLIENT_SECRET) whenever(email).thenReturn("[email protected]") } linkAccountManager = mock<LinkAccountManager>().apply { whenever(linkAccount).thenReturn(MutableStateFlow(mockLinkAccount)) } } @After fun tearDown() { Dispatchers.resetMain() } @Test fun `On initialization start collecting CardEdit result`() = runTest { createViewModel() verify(navigator).getResultFlow<PaymentDetailsResult>(any()) } @Test fun `On initialization payment details are loaded`() = runTest { val card1 = mock<ConsumerPaymentDetails.Card>() val card2 = mock<ConsumerPaymentDetails.Card>() val paymentDetails = mock<ConsumerPaymentDetails>() whenever(paymentDetails.paymentDetails).thenReturn(listOf(card1, card2)) whenever(linkAccountManager.listPaymentDetails()) .thenReturn(Result.success(paymentDetails)) val viewModel = createViewModel() assertThat(viewModel.uiState.value.paymentDetailsList).containsExactly(card1, card2) } @Test fun `On initialization when no payment details then navigate to AddPaymentMethod`() = runTest { val response = mock<ConsumerPaymentDetails>() whenever(response.paymentDetails).thenReturn(emptyList()) whenever(linkAccountManager.listPaymentDetails()) .thenReturn(Result.success(response)) createViewModel() verify(navigator).navigateTo(argWhere { it is LinkScreen.PaymentMethod }, eq(true)) } @Test fun `On initialization when prefilledCardParams is not null then navigate to AddPaymentMethod`() = runTest { whenever(args.prefilledCardParams).thenReturn(mock()) whenever(linkAccountManager.listPaymentDetails()) .thenReturn(Result.success(CONSUMER_PAYMENT_DETAILS)) createViewModel() verify(navigator).navigateTo( argWhere { it.route == LinkScreen.PaymentMethod(true).route }, eq(false) ) } @Test fun `onSelectedPaymentDetails starts payment confirmation`() = runTest { val paymentDetails = CONSUMER_PAYMENT_DETAILS.paymentDetails.first() whenever(linkAccountManager.listPaymentDetails()) .thenReturn(Result.success(CONSUMER_PAYMENT_DETAILS)) whenever(args.shippingValues) .thenReturn(null) val viewModel = createViewModel() viewModel.onItemSelected(paymentDetails) viewModel.onConfirmPayment() val paramsCaptor = argumentCaptor<ConfirmStripeIntentParams>() verify(confirmationManager).confirmStripeIntent(paramsCaptor.capture(), any()) assertThat(paramsCaptor.firstValue).isEqualTo( ConfirmPaymentIntentParams.createWithPaymentMethodCreateParams( PaymentMethodCreateParams.createLink( paymentDetails.id, CLIENT_SECRET ), StripeIntentFixtures.PI_SUCCEEDED.clientSecret!! ) ) } @Test fun `when shippingValues are passed ConfirmPaymentIntentParams has shipping`() = runTest { whenever(linkAccountManager.listPaymentDetails()) .thenReturn(Result.success(CONSUMER_PAYMENT_DETAILS)) whenever(args.shippingValues).thenReturn( mapOf( IdentifierSpec.Name to "Test Name", IdentifierSpec.Country to "US" ) ) val viewModel = createViewModel() viewModel.onConfirmPayment() val paramsCaptor = argumentCaptor<ConfirmStripeIntentParams>() verify(confirmationManager).confirmStripeIntent(paramsCaptor.capture(), any()) assertThat(paramsCaptor.firstValue.toParamMap()["shipping"]).isEqualTo( mapOf( "address" to mapOf( "country" to "US" ), "name" to "Test Name" ) ) } @Test fun `onItemSelected updates selected item`() { val paymentDetails = CONSUMER_PAYMENT_DETAILS.paymentDetails.first() val viewModel = createViewModel() viewModel.onItemSelected(paymentDetails) assertThat(viewModel.uiState.value.selectedItem).isEqualTo(paymentDetails) } @Test fun `when selected item is removed then default item is selected`() = runTest { val deletedPaymentDetails = CONSUMER_PAYMENT_DETAILS.paymentDetails[1] val viewModel = createViewModel() viewModel.onItemSelected(deletedPaymentDetails) assertThat(viewModel.uiState.value.selectedItem).isEqualTo(deletedPaymentDetails) whenever(linkAccountManager.deletePaymentDetails(anyOrNull())) .thenReturn(Result.success(Unit)) whenever(linkAccountManager.listPaymentDetails()) .thenReturn( Result.success( CONSUMER_PAYMENT_DETAILS.copy( paymentDetails = CONSUMER_PAYMENT_DETAILS.paymentDetails .filter { it != deletedPaymentDetails } ) ) ) viewModel.deletePaymentMethod(deletedPaymentDetails) assertThat(viewModel.uiState.value.selectedItem) .isEqualTo(CONSUMER_PAYMENT_DETAILS.paymentDetails.first()) } @Test fun `when default item is not supported then first supported item is selected`() = runTest { whenever(args.stripeIntent).thenReturn( StripeIntentFixtures.PI_SUCCEEDED.copy( linkFundingSources = listOf(ConsumerPaymentDetails.BankAccount.type) ) ) whenever(linkAccountManager.listPaymentDetails()) .thenReturn(Result.success(CONSUMER_PAYMENT_DETAILS)) val viewModel = createViewModel() val bankAccount = CONSUMER_PAYMENT_DETAILS.paymentDetails[2] assertThat(viewModel.uiState.value.selectedItem).isEqualTo(bankAccount) } @Test fun `when payment confirmation fails then an error message is shown`() { val errorThrown = "Error message" val viewModel = createViewModel() viewModel.onItemSelected(CONSUMER_PAYMENT_DETAILS.paymentDetails.first()) viewModel.onConfirmPayment() val callbackCaptor = argumentCaptor<PaymentConfirmationCallback>() verify(confirmationManager).confirmStripeIntent(any(), callbackCaptor.capture()) callbackCaptor.firstValue(Result.success(PaymentResult.Failed(RuntimeException(errorThrown)))) assertThat(viewModel.uiState.value.errorMessage).isEqualTo(ErrorMessage.Raw(errorThrown)) } @Test fun `deletePaymentMethod fetches payment details and stays expanded when successful`() = runTest { val paymentDetails = CONSUMER_PAYMENT_DETAILS whenever(linkAccountManager.listPaymentDetails()) .thenReturn(Result.success(paymentDetails)) val viewModel = createViewModel() verify(linkAccountManager).listPaymentDetails() clearInvocations(linkAccountManager) viewModel.setExpanded(true) // Initially has two elements assertThat(viewModel.uiState.value.paymentDetailsList) .containsExactlyElementsIn(paymentDetails.paymentDetails) whenever(linkAccountManager.deletePaymentDetails(anyOrNull())) .thenReturn(Result.success(Unit)) // Delete the first element viewModel.deletePaymentMethod(paymentDetails.paymentDetails.first()) // Fetches payment details again verify(linkAccountManager).listPaymentDetails() assertThat(viewModel.uiState.value.isExpanded).isTrue() } @Test fun `when selected payment method is not supported then wallet is expanded`() = runTest { // One card and one bank account val paymentDetails = CONSUMER_PAYMENT_DETAILS.copy( paymentDetails = listOf( CONSUMER_PAYMENT_DETAILS.paymentDetails[1], CONSUMER_PAYMENT_DETAILS.paymentDetails[2] ) ) whenever(linkAccountManager.listPaymentDetails()) .thenReturn(Result.success(paymentDetails)) val viewModel = createViewModel() assertThat(viewModel.uiState.value.paymentDetailsList) .containsExactlyElementsIn(paymentDetails.paymentDetails) // First item is default, so it should be selected and the list should be collapsed val defaultItem = paymentDetails.paymentDetails.first() assertThat(viewModel.uiState.value.selectedItem).isEqualTo(defaultItem) assertThat(viewModel.uiState.value.isExpanded).isFalse() whenever(linkAccountManager.deletePaymentDetails(anyOrNull())) .thenReturn(Result.success(Unit)) // Only the bank account is returned, which is not supported whenever(linkAccountManager.listPaymentDetails()).thenReturn( Result.success( paymentDetails.copy(paymentDetails = listOf(paymentDetails.paymentDetails[1])) ) ) // Delete the selected item viewModel.deletePaymentMethod(defaultItem) assertThat(viewModel.uiState.value.isExpanded).isTrue() } @Test fun `when payment method deletion fails then an error message is shown`() = runTest { whenever(linkAccountManager.listPaymentDetails()) .thenReturn(Result.success(CONSUMER_PAYMENT_DETAILS)) val errorThrown = "Error message" val viewModel = createViewModel() whenever(linkAccountManager.deletePaymentDetails(anyOrNull())) .thenReturn(Result.failure(RuntimeException(errorThrown))) viewModel.deletePaymentMethod(CONSUMER_PAYMENT_DETAILS.paymentDetails.first()) assertThat(viewModel.uiState.value.errorMessage).isEqualTo(ErrorMessage.Raw(errorThrown)) } @Test fun `onSelectedPaymentDetails dismisses on success`() = runTest { whenever(confirmationManager.confirmStripeIntent(any(), any())).thenAnswer { invocation -> (invocation.getArgument(1) as? PaymentConfirmationCallback)?.let { it(Result.success(PaymentResult.Completed)) } } whenever(linkAccountManager.listPaymentDetails()) .thenReturn(Result.success(CONSUMER_PAYMENT_DETAILS)) val viewModel = createViewModel() viewModel.onConfirmPayment() assertThat(viewModel.uiState.value.primaryButtonState).isEqualTo(PrimaryButtonState.Completed) advanceTimeBy(PrimaryButtonState.COMPLETED_DELAY_MS + 1) verify(navigator).dismiss(LinkActivityResult.Completed) } @Test fun `Pay another way dismisses Link`() { val viewModel = createViewModel() viewModel.payAnotherWay() verify(navigator).cancel(reason = eq(Reason.PayAnotherWay)) verify(linkAccountManager, never()).logout() } @Test fun `Add new payment method navigates to AddPaymentMethod screen`() { val viewModel = createViewModel() viewModel.addNewPaymentMethod() verify(navigator).navigateTo(argWhere { it is LinkScreen.PaymentMethod }, eq(false)) } @Test fun `Update payment method navigates to CardEdit screen`() = runTest { val paymentDetails = CONSUMER_PAYMENT_DETAILS whenever(linkAccountManager.listPaymentDetails()) .thenReturn(Result.success(paymentDetails)) val viewModel = createViewModel() viewModel.editPaymentMethod(paymentDetails.paymentDetails.first()) verify(navigator).navigateTo( argWhere { it.route.startsWith(LinkScreen.CardEdit.route.substringBefore('?')) }, any() ) } @Test fun `On CardEdit result successful then it reloads payment details`() = runTest { val flow = MutableStateFlow<PaymentDetailsResult?>(null) whenever(navigator.getResultFlow<PaymentDetailsResult>(any())).thenReturn(flow) createViewModel() verify(linkAccountManager).listPaymentDetails() clearInvocations(linkAccountManager) flow.emit(PaymentDetailsResult.Success("")) verify(linkAccountManager).listPaymentDetails() } @Test fun `On CardEdit result failure then it shows error`() = runTest { val flow = MutableStateFlow<PaymentDetailsResult?>(null) whenever(navigator.getResultFlow<PaymentDetailsResult>(any())).thenReturn(flow) val viewModel = createViewModel() val error = ErrorMessage.Raw("Error message") flow.emit(PaymentDetailsResult.Failure(error)) assertThat(viewModel.uiState.value.errorMessage).isEqualTo(error) } @Test fun `Sends CVC if paying with card that requires CVC recollection`() = runTest { val paymentDetails = mockCard(cvcCheck = CvcCheck.Fail) val viewModel = createViewModel() val cvcInput = "123" viewModel.onItemSelected(paymentDetails) viewModel.cvcController.onRawValueChange(cvcInput) viewModel.onConfirmPayment() val paramsCaptor = argumentCaptor<ConfirmStripeIntentParams>() verify(confirmationManager).confirmStripeIntent(paramsCaptor.capture(), any()) val paymentIntentParams = paramsCaptor.firstValue as ConfirmPaymentIntentParams val paramsMap = paymentIntentParams.paymentMethodCreateParams!!.toParamMap() val link = paramsMap["link"] as Map<*, *> val card = link["card"] as Map<*, *> val cvc = card["cvc"] assertThat(cvc).isEqualTo(cvcInput) } @Test fun `Does not send CVC if paying with card that does not require CVC recollection`() = runTest { whenever(linkAccountManager.listPaymentDetails()) .thenReturn(Result.success(CONSUMER_PAYMENT_DETAILS)) val paymentDetails = mockCard(cvcCheck = CvcCheck.Pass) val viewModel = createViewModel() viewModel.onItemSelected(paymentDetails) viewModel.onConfirmPayment() val paramsCaptor = argumentCaptor<ConfirmStripeIntentParams>() verify(confirmationManager).confirmStripeIntent(paramsCaptor.capture(), any()) val paymentIntentParams = paramsCaptor.firstValue as ConfirmPaymentIntentParams val paramsMap = paymentIntentParams.paymentMethodCreateParams!!.toParamMap() val link = paramsMap["link"] as Map<*, *> assertThat(link).doesNotContainKey("card") } @Test fun `Updates payment details when paying with expired card`() = runTest { val expiredCard = mockCard(isExpired = true) val viewModel = createViewModel() viewModel.onItemSelected(expiredCard) viewModel.expiryDateController.onRawValueChange("1230") viewModel.cvcController.onRawValueChange("123") viewModel.onConfirmPayment() val paramsCaptor = argumentCaptor<ConsumerPaymentDetailsUpdateParams>() verify(linkAccountManager).updatePaymentDetails(paramsCaptor.capture()) val paramsMap = paramsCaptor.firstValue.toParamMap() assertThat(paramsMap["exp_month"]).isEqualTo("12") assertThat(paramsMap["exp_year"]).isEqualTo("2030") } @Test fun `Shows alert dialog if updating expired card info fails`() = runTest { whenever(linkAccountManager.updatePaymentDetails(any())) .thenReturn(Result.failure(APIConnectionException())) val expiredCard = mockCard(isExpired = true) val viewModel = createViewModel() viewModel.onItemSelected(expiredCard) viewModel.expiryDateController.onRawValueChange("1230") viewModel.cvcController.onRawValueChange("123") viewModel.onConfirmPayment() assertThat(viewModel.uiState.value.alertMessage).isEqualTo( ErrorMessage.FromResources(R.string.stripe_failure_connection_error) ) } @Test fun `Resets expiry date and CVC controllers when new payment method is selected`() = runTest { val paymentDetails = CONSUMER_PAYMENT_DETAILS.paymentDetails[1] whenever(linkAccountManager.listPaymentDetails()) .thenReturn(Result.success(CONSUMER_PAYMENT_DETAILS)) val viewModel = createViewModel().apply { expiryDateController.onRawValueChange("1230") cvcController.onRawValueChange("123") } viewModel.onItemSelected(paymentDetails) val uiState = viewModel.uiState.value assertThat(uiState.expiryDateInput).isEqualTo(FormFieldEntry(value = "")) assertThat(uiState.cvcInput).isEqualTo(FormFieldEntry(value = "")) } @Test fun `Expiry date and CVC values are kept when existing payment method is selected`() = runTest { val paymentDetails = CONSUMER_PAYMENT_DETAILS.paymentDetails.first() whenever(linkAccountManager.listPaymentDetails()) .thenReturn(Result.success(CONSUMER_PAYMENT_DETAILS)) val viewModel = createViewModel().apply { expiryDateController.onRawValueChange("1230") cvcController.onRawValueChange("123") } viewModel.onItemSelected(paymentDetails) val uiState = viewModel.uiState.value assertThat(uiState.expiryDateInput.value).isEqualTo("1230") assertThat(uiState.cvcInput.value).isEqualTo("123") } @Test fun `Updates payment method default selection correctly`() = runTest { val originalPaymentDetails = mockCard(isDefault = false) val updatedPaymentDetails = originalPaymentDetails.copy(isDefault = true) val originalResponse = CONSUMER_PAYMENT_DETAILS.copy( paymentDetails = CONSUMER_PAYMENT_DETAILS.paymentDetails.dropLast(1) + originalPaymentDetails ) val updateResponse = CONSUMER_PAYMENT_DETAILS.copy( paymentDetails = listOf(updatedPaymentDetails) ) whenever(linkAccountManager.listPaymentDetails()) .thenReturn(Result.success(originalResponse)) whenever(linkAccountManager.updatePaymentDetails(any())) .thenReturn(Result.success(updateResponse)) val viewModel = createViewModel() viewModel.uiState.test { // We need to skip the initial UI state skipItems(1) viewModel.setDefault(originalPaymentDetails) val loadingUiState = awaitItem() assertThat(loadingUiState.paymentMethodIdBeingUpdated).isEqualTo(originalPaymentDetails.id) val finalUiState = awaitItem() assertThat(finalUiState.paymentMethodIdBeingUpdated).isNull() assertThat( finalUiState.paymentDetailsList.filter { it.isDefault }.size ).isEqualTo(1) assertThat( finalUiState.paymentDetailsList.single { it.isDefault } ).isEqualTo(updatedPaymentDetails) } } @Test fun `Factory gets initialized by Injector`() { val mockBuilder = mock<SignedInViewModelSubcomponent.Builder>() val mockSubComponent = mock<SignedInViewModelSubcomponent>() val vmToBeReturned = mock<WalletViewModel>() whenever(mockBuilder.linkAccount(any())).thenReturn(mockBuilder) whenever(mockBuilder.build()).thenReturn(mockSubComponent) whenever((mockSubComponent.walletViewModel)).thenReturn(vmToBeReturned) val mockSavedStateRegistryOwner = mock<SavedStateRegistryOwner>() val mockSavedStateRegistry = mock<SavedStateRegistry>() val mockLifeCycle = mock<Lifecycle>() whenever(mockSavedStateRegistryOwner.savedStateRegistry).thenReturn(mockSavedStateRegistry) whenever(mockSavedStateRegistryOwner.lifecycle).thenReturn(mockLifeCycle) whenever(mockLifeCycle.currentState).thenReturn(Lifecycle.State.CREATED) val injector = object : NonFallbackInjector { override fun inject(injectable: Injectable<*>) { val factory = injectable as WalletViewModel.Factory factory.subComponentBuilderProvider = Provider { mockBuilder } } } val factory = WalletViewModel.Factory( mock(), injector ) val factorySpy = spy(factory) val createdViewModel = factorySpy.create(WalletViewModel::class.java) assertThat(createdViewModel).isEqualTo(vmToBeReturned) } private fun createViewModel() = WalletViewModel( args, linkAccountManager, navigator, confirmationManager, logger ) private fun mockCard( cvcCheck: CvcCheck = CvcCheck.Pass, isExpired: Boolean = false, isDefault: Boolean = true ): ConsumerPaymentDetails.Card { val id = Random.nextInt() val currentYear = Calendar.getInstance().get(Calendar.YEAR) val expiryYear = if (isExpired) currentYear - 1 else currentYear + 1 return ConsumerPaymentDetails.Card( id = "id_$id", isDefault = isDefault, expiryYear = expiryYear, expiryMonth = 12, brand = CardBrand.Visa, last4 = "4242", cvcCheck = cvcCheck ) } companion object { const val CLIENT_SECRET = "client_secret" } }
mit
c53778d0bd4f48ecd96fa49c590ead11
37.084977
105
0.688581
5.335459
false
true
false
false
AndroidX/androidx
compose/material/material/samples/src/main/java/androidx/compose/material/samples/DrawerSamples.kt
3
5353
/* * 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.compose.material.samples import androidx.annotation.Sampled import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.selection.toggleable import androidx.compose.material.BottomDrawer import androidx.compose.material.BottomDrawerValue import androidx.compose.material.Button import androidx.compose.material.Checkbox import androidx.compose.material.DrawerValue import androidx.compose.material.ExperimentalMaterialApi import androidx.compose.material.Icon import androidx.compose.material.ListItem import androidx.compose.material.ModalDrawer import androidx.compose.material.Text import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Favorite import androidx.compose.material.rememberBottomDrawerState import androidx.compose.material.rememberDrawerState import androidx.compose.runtime.Composable import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import kotlinx.coroutines.launch @Sampled @Composable fun ModalDrawerSample() { val drawerState = rememberDrawerState(DrawerValue.Closed) val scope = rememberCoroutineScope() ModalDrawer( drawerState = drawerState, drawerContent = { Button( modifier = Modifier.align(Alignment.CenterHorizontally).padding(top = 16.dp), onClick = { scope.launch { drawerState.close() } }, content = { Text("Close Drawer") } ) }, content = { Column( modifier = Modifier.fillMaxSize().padding(16.dp), horizontalAlignment = Alignment.CenterHorizontally ) { Text(text = if (drawerState.isClosed) ">>> Swipe >>>" else "<<< Swipe <<<") Spacer(Modifier.height(20.dp)) Button(onClick = { scope.launch { drawerState.open() } }) { Text("Click to open") } } } ) } @Sampled @Composable @OptIn(ExperimentalMaterialApi::class) fun BottomDrawerSample() { val (gesturesEnabled, toggleGesturesEnabled) = remember { mutableStateOf(true) } val scope = rememberCoroutineScope() Column { Row( modifier = Modifier.fillMaxWidth().toggleable( value = gesturesEnabled, onValueChange = toggleGesturesEnabled ) ) { Checkbox(gesturesEnabled, null) Text(text = if (gesturesEnabled) "Gestures Enabled" else "Gestures Disabled") } val drawerState = rememberBottomDrawerState(BottomDrawerValue.Closed) BottomDrawer( gesturesEnabled = gesturesEnabled, drawerState = drawerState, drawerContent = { Button( modifier = Modifier.align(Alignment.CenterHorizontally).padding(top = 16.dp), onClick = { scope.launch { drawerState.close() } }, content = { Text("Close Drawer") } ) LazyColumn { items(25) { ListItem( text = { Text("Item $it") }, icon = { Icon( Icons.Default.Favorite, contentDescription = "Localized description" ) } ) } } }, content = { Column( modifier = Modifier.fillMaxSize().padding(16.dp), horizontalAlignment = Alignment.CenterHorizontally ) { val openText = if (gesturesEnabled) "▲▲▲ Pull up ▲▲▲" else "Click the button!" Text(text = if (drawerState.isClosed) openText else "▼▼▼ Drag down ▼▼▼") Spacer(Modifier.height(20.dp)) Button(onClick = { scope.launch { drawerState.open() } }) { Text("Click to open") } } } ) } }
apache-2.0
b4bf74ecde09cfbab608e142ff229d43
38.191176
98
0.619628
5.143822
false
false
false
false
AndroidX/androidx
paging/paging-runtime/src/main/java/androidx/paging/NullPaddedListDiffHelper.kt
3
22879
/* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.paging import androidx.paging.DiffingChangePayload.ITEM_TO_PLACEHOLDER import androidx.paging.DiffingChangePayload.PLACEHOLDER_POSITION_CHANGE import androidx.paging.DiffingChangePayload.PLACEHOLDER_TO_ITEM import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.ListUpdateCallback import androidx.recyclerview.widget.RecyclerView /** * Methods for computing and applying DiffResults between PagedLists. * * To minimize the amount of diffing caused by placeholders, we only execute DiffUtil in a reduced * 'diff space' - in the range (computeLeadingNulls..size-computeTrailingNulls). * * This allows the diff of a PagedList, e.g.: * 100 nulls, placeholder page, (empty page) x 5, page, 100 nulls * * To only inform DiffUtil about single loaded page in this case, by pruning all other nulls from * consideration. */ internal fun <T : Any> NullPaddedList<T>.computeDiff( newList: NullPaddedList<T>, diffCallback: DiffUtil.ItemCallback<T> ): NullPaddedDiffResult { val oldSize = storageCount val newSize = newList.storageCount val diffResult = DiffUtil.calculateDiff( object : DiffUtil.Callback() { override fun getChangePayload(oldItemPosition: Int, newItemPosition: Int): Any? { val oldItem = getFromStorage(oldItemPosition) val newItem = newList.getFromStorage(newItemPosition) return when { oldItem === newItem -> true else -> diffCallback.getChangePayload(oldItem, newItem) } } override fun getOldListSize() = oldSize override fun getNewListSize() = newSize override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean { val oldItem = getFromStorage(oldItemPosition) val newItem = newList.getFromStorage(newItemPosition) return when { oldItem === newItem -> true else -> diffCallback.areItemsTheSame(oldItem, newItem) } } override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean { val oldItem = getFromStorage(oldItemPosition) val newItem = newList.getFromStorage(newItemPosition) return when { oldItem === newItem -> true else -> diffCallback.areContentsTheSame(oldItem, newItem) } } }, true ) // find first overlap val hasOverlap = (0 until storageCount).any { diffResult.convertOldPositionToNew(it) != RecyclerView.NO_POSITION } return NullPaddedDiffResult( diff = diffResult, hasOverlap = hasOverlap ) } private class OffsettingListUpdateCallback internal constructor( private val offset: Int, private val callback: ListUpdateCallback ) : ListUpdateCallback { override fun onInserted(position: Int, count: Int) { callback.onInserted(position + offset, count) } override fun onRemoved(position: Int, count: Int) { callback.onRemoved(position + offset, count) } override fun onMoved(fromPosition: Int, toPosition: Int) { callback.onMoved(fromPosition + offset, toPosition + offset) } override fun onChanged(position: Int, count: Int, payload: Any?) { callback.onChanged(position + offset, count, payload) } } /** * See NullPaddedDiffing.md for how this works and why it works that way :). * * Note: if lists mutate between diffing the snapshot and dispatching the diff here, then we * handle this by passing the snapshot to the callback, and dispatching those changes * immediately after dispatching this diff. */ internal fun <T : Any> NullPaddedList<T>.dispatchDiff( callback: ListUpdateCallback, newList: NullPaddedList<T>, diffResult: NullPaddedDiffResult ) { if (diffResult.hasOverlap) { OverlappingListsDiffDispatcher.dispatchDiff( oldList = this, newList = newList, callback = callback, diffResult = diffResult, ) } else { // if no values overlapped between two lists, use change with payload *unless* the // position represents real items in both old and new lists in which case *change* would // be misleading hence we need to dispatch add/remove. DistinctListsDiffDispatcher.dispatchDiff( callback = callback, oldList = this, newList = newList, ) } } /** * Given an oldPosition representing an anchor in the old data set, computes its new position * after the diff, or a guess if it no longer exists. */ internal fun NullPaddedList<*>.transformAnchorIndex( diffResult: NullPaddedDiffResult, newList: NullPaddedList<*>, oldPosition: Int ): Int { if (!diffResult.hasOverlap) { // if lists didn't overlap, use old position return oldPosition.coerceIn(0 until newList.size) } // diffResult's indices starting after nulls, need to transform to diffutil indices // (see also dispatchDiff(), which adds this offset when dispatching) val diffIndex = oldPosition - placeholdersBefore val oldSize = storageCount // if our anchor is non-null, use it or close item's position in new list if (diffIndex in 0 until oldSize) { // search outward from old position for position that maps for (i in 0..29) { val positionToTry = diffIndex + i / 2 * if (i % 2 == 1) -1 else 1 // reject if (null) item was not passed to DiffUtil, and wouldn't be in the result if (positionToTry < 0 || positionToTry >= storageCount) { continue } val result = diffResult.diff.convertOldPositionToNew(positionToTry) if (result != -1) { // also need to transform from diffutil output indices to newList return result + newList.placeholdersBefore } } } // not anchored to an item in new list, so just reuse position (clamped to newList size) return oldPosition.coerceIn(0 until newList.size) } internal class NullPaddedDiffResult( val diff: DiffUtil.DiffResult, // true if two lists have at least 1 item the same val hasOverlap: Boolean ) /** * Helper class to implement the heuristic documented in NullPaddedDiffing.md. */ internal object OverlappingListsDiffDispatcher { fun <T> dispatchDiff( oldList: NullPaddedList<T>, newList: NullPaddedList<T>, callback: ListUpdateCallback, diffResult: NullPaddedDiffResult ) { val callbackWrapper = PlaceholderUsingUpdateCallback( oldList = oldList, newList = newList, callback = callback ) diffResult.diff.dispatchUpdatesTo(callbackWrapper) callbackWrapper.fixPlaceholders() } @Suppress("NOTHING_TO_INLINE") private class PlaceholderUsingUpdateCallback<T>( private val oldList: NullPaddedList<T>, private val newList: NullPaddedList<T>, private val callback: ListUpdateCallback ) : ListUpdateCallback { // These variables hold the "current" value for placeholders and storage count and are // updated as we dispatch notify events to `callback`. private var placeholdersBefore = oldList.placeholdersBefore private var placeholdersAfter = oldList.placeholdersAfter private var storageCount = oldList.storageCount // Track if we used placeholders for a certain case to avoid using them for both additions // and removals at the same time, which might end up sending misleading change events. private var placeholdersBeforeState = UNUSED private var placeholdersAfterState = UNUSED /** * Offsets a value based on placeholders to make it suitable to pass into the callback. */ private inline fun Int.offsetForDispatch() = this + placeholdersBefore fun fixPlaceholders() { // add / remove placeholders to match the new list fixLeadingPlaceholders() fixTrailingPlaceholders() } private fun fixTrailingPlaceholders() { // the #of placeholders that didn't have any updates. We might need to send position // change events for them if their original positions are no longer valid. var unchangedPlaceholders = minOf(oldList.placeholdersAfter, placeholdersAfter) val postPlaceholdersToAdd = newList.placeholdersAfter - placeholdersAfter val runningListSize = placeholdersBefore + storageCount + placeholdersAfter // check if unchanged placeholders changed their positions between two lists val unchangedPlaceholdersStartPos = runningListSize - unchangedPlaceholders val unchangedPlaceholdersMoved = unchangedPlaceholdersStartPos != (oldList.size - unchangedPlaceholders) if (postPlaceholdersToAdd > 0) { // always add to the end of the list callback.onInserted(runningListSize, postPlaceholdersToAdd) } else if (postPlaceholdersToAdd < 0) { // always remove from the end // notice that postPlaceholdersToAdd is negative, thats why it is added to // runningListEnd callback.onRemoved( runningListSize + postPlaceholdersToAdd, -postPlaceholdersToAdd ) // remove them from unchanged placeholders, notice that it is an addition because // postPlaceholdersToAdd is negative unchangedPlaceholders += postPlaceholdersToAdd } if (unchangedPlaceholders > 0 && unchangedPlaceholdersMoved) { // These placeholders didn't get any change event yet their list positions changed. // We should send an update as the position of a placeholder is part of its data. callback.onChanged( unchangedPlaceholdersStartPos, unchangedPlaceholders, PLACEHOLDER_POSITION_CHANGE ) } placeholdersAfter = newList.placeholdersAfter } private fun fixLeadingPlaceholders() { // the #of placeholders that didn't have any updates. We might need to send position // change events if we further modify the list. val unchangedPlaceholders = minOf(oldList.placeholdersBefore, placeholdersBefore) val prePlaceholdersToAdd = newList.placeholdersBefore - placeholdersBefore if (prePlaceholdersToAdd > 0) { if (unchangedPlaceholders > 0) { // these will be shifted down so send a change event for them callback.onChanged(0, unchangedPlaceholders, PLACEHOLDER_POSITION_CHANGE) } // always insert to the beginning of the list callback.onInserted(0, prePlaceholdersToAdd) } else if (prePlaceholdersToAdd < 0) { // always remove from the beginning of the list callback.onRemoved(0, -prePlaceholdersToAdd) if (unchangedPlaceholders + prePlaceholdersToAdd > 0) { // these have been shifted up, send a change event for them. We add the negative // number of `prePlaceholdersToAdd` not to send change events for them callback.onChanged( 0, unchangedPlaceholders + prePlaceholdersToAdd, PLACEHOLDER_POSITION_CHANGE ) } } placeholdersBefore = newList.placeholdersBefore } override fun onInserted(position: Int, count: Int) { when { dispatchInsertAsPlaceholderAfter(position, count) -> { // dispatched as placeholders after } dispatchInsertAsPlaceholderBefore(position, count) -> { // dispatched as placeholders before } else -> { // not at the edge, dispatch as usual callback.onInserted(position.offsetForDispatch(), count) } } storageCount += count } /** * Return true if it is dispatched, false otherwise. */ private fun dispatchInsertAsPlaceholderBefore(position: Int, count: Int): Boolean { if (position > 0) { return false // not at the edge } if (placeholdersBeforeState == USED_FOR_REMOVAL) { return false } val asPlaceholderChange = minOf(count, placeholdersBefore) if (asPlaceholderChange > 0) { placeholdersBeforeState = USED_FOR_ADDITION // this index is negative because we are going back. offsetForDispatch will fix it val index = (0 - asPlaceholderChange) callback.onChanged( index.offsetForDispatch(), asPlaceholderChange, PLACEHOLDER_TO_ITEM ) placeholdersBefore -= asPlaceholderChange } val asInsert = count - asPlaceholderChange if (asInsert > 0) { callback.onInserted( 0.offsetForDispatch(), asInsert ) } return true } /** * Return true if it is dispatched, false otherwise. */ private fun dispatchInsertAsPlaceholderAfter(position: Int, count: Int): Boolean { if (position < storageCount) { return false // not at the edge } if (placeholdersAfterState == USED_FOR_REMOVAL) { return false } val asPlaceholderChange = minOf(count, placeholdersAfter) if (asPlaceholderChange > 0) { placeholdersAfterState = USED_FOR_ADDITION callback.onChanged( position.offsetForDispatch(), asPlaceholderChange, PLACEHOLDER_TO_ITEM ) placeholdersAfter -= asPlaceholderChange } val asInsert = count - asPlaceholderChange if (asInsert > 0) { callback.onInserted( (position + asPlaceholderChange).offsetForDispatch(), asInsert ) } return true } override fun onRemoved(position: Int, count: Int) { when { dispatchRemovalAsPlaceholdersAfter(position, count) -> { // dispatched as changed into placeholder } dispatchRemovalAsPlaceholdersBefore(position, count) -> { // dispatched as changed into placeholder } else -> { // fallback, need to handle here callback.onRemoved(position.offsetForDispatch(), count) } } storageCount -= count } /** * Return true if it is dispatched, false otherwise. */ private fun dispatchRemovalAsPlaceholdersBefore(position: Int, count: Int): Boolean { if (position > 0) { return false } if (placeholdersBeforeState == USED_FOR_ADDITION) { return false } // see how many removals we can convert to change. // make sure we don't end up having too many placeholders that we'll end up removing // anyways val maxPlaceholdersToAdd = newList.placeholdersBefore - placeholdersBefore val asPlaceholders = minOf(maxPlaceholdersToAdd, count).coerceAtLeast(0) val asRemoval = count - asPlaceholders // first remove then use placeholders to make sure items that are closer to the loaded // content center are more likely to stay in the list if (asRemoval > 0) { callback.onRemoved(0.offsetForDispatch(), asRemoval) } if (asPlaceholders > 0) { placeholdersBeforeState = USED_FOR_REMOVAL callback.onChanged( 0.offsetForDispatch(), asPlaceholders, ITEM_TO_PLACEHOLDER ) placeholdersBefore += asPlaceholders } return true } /** * Return true if it is dispatched, false otherwise. */ private fun dispatchRemovalAsPlaceholdersAfter(position: Int, count: Int): Boolean { val end = position + count if (end < storageCount) { return false // not at the edge } if (placeholdersAfterState == USED_FOR_ADDITION) { return false } // see how many removals we can convert to change. // make sure we don't end up having too many placeholders that we'll end up removing // anyways val maxPlaceholdersToAdd = newList.placeholdersAfter - placeholdersAfter val asPlaceholders = minOf(maxPlaceholdersToAdd, count).coerceAtLeast(0) val asRemoval = count - asPlaceholders // first use placeholders then removal to make sure items that are closer to // the loaded content center are more likely to stay in the list if (asPlaceholders > 0) { placeholdersAfterState = USED_FOR_REMOVAL callback.onChanged( position.offsetForDispatch(), asPlaceholders, ITEM_TO_PLACEHOLDER ) placeholdersAfter += asPlaceholders } if (asRemoval > 0) { callback.onRemoved((position + asPlaceholders).offsetForDispatch(), asRemoval) } return true } override fun onMoved(fromPosition: Int, toPosition: Int) { callback.onMoved(fromPosition.offsetForDispatch(), toPosition.offsetForDispatch()) } override fun onChanged(position: Int, count: Int, payload: Any?) { callback.onChanged(position.offsetForDispatch(), count, payload) } companion object { // markers for edges to avoid using them for both additions and removals private const val UNUSED = 1 private const val USED_FOR_REMOVAL = UNUSED + 1 private const val USED_FOR_ADDITION = USED_FOR_REMOVAL + 1 } } } /** * Helper object to dispatch diffs when two lists do not overlap at all. * * We try to send change events when an item's position is replaced with a placeholder or vice * versa. * If there is an item in a given position in before and after lists, we dispatch add/remove for * them not to trigger unexpected change animations. */ internal object DistinctListsDiffDispatcher { fun <T : Any> dispatchDiff( callback: ListUpdateCallback, oldList: NullPaddedList<T>, newList: NullPaddedList<T>, ) { val storageOverlapStart = maxOf( oldList.placeholdersBefore, newList.placeholdersBefore ) val storageOverlapEnd = minOf( oldList.placeholdersBefore + oldList.storageCount, newList.placeholdersBefore + newList.storageCount ) // we need to dispatch add/remove for overlapping storage positions val overlappingStorageSize = storageOverlapEnd - storageOverlapStart if (overlappingStorageSize > 0) { callback.onRemoved(storageOverlapStart, overlappingStorageSize) callback.onInserted(storageOverlapStart, overlappingStorageSize) } // now everything else is good as a change animation. // make sure to send a change for old items whose positions are still in the list // to handle cases where there is no overlap, we min/max boundaries val changeEventStartBoundary = minOf(storageOverlapStart, storageOverlapEnd) val changeEventEndBoundary = maxOf(storageOverlapStart, storageOverlapEnd) dispatchChange( callback = callback, startBoundary = changeEventStartBoundary, endBoundary = changeEventEndBoundary, start = oldList.placeholdersBefore.coerceAtMost(newList.size), end = (oldList.placeholdersBefore + oldList.storageCount).coerceAtMost(newList.size), payload = ITEM_TO_PLACEHOLDER ) // now for new items that were mapping to placeholders, send change events dispatchChange( callback = callback, startBoundary = changeEventStartBoundary, endBoundary = changeEventEndBoundary, start = newList.placeholdersBefore.coerceAtMost(oldList.size), end = (newList.placeholdersBefore + newList.storageCount).coerceAtMost(oldList.size), payload = PLACEHOLDER_TO_ITEM ) // finally, fix the size val itemsToAdd = newList.size - oldList.size if (itemsToAdd > 0) { callback.onInserted(oldList.size, itemsToAdd) } else if (itemsToAdd < 0) { callback.onRemoved(oldList.size + itemsToAdd, -itemsToAdd) } } private fun dispatchChange( callback: ListUpdateCallback, startBoundary: Int, endBoundary: Int, start: Int, end: Int, payload: Any ) { val beforeOverlapCount = startBoundary - start if (beforeOverlapCount > 0) { callback.onChanged(start, beforeOverlapCount, payload) } val afterOverlapCount = end - endBoundary if (afterOverlapCount > 0) { callback.onChanged(endBoundary, afterOverlapCount, payload) } } }
apache-2.0
939995e53feebcc2d238fe4fd1e6575e
40.447464
100
0.616504
5.307121
false
false
false
false
ebean-orm-examples/example-kotlin
src/test/kotlin/org/example/domain/CustomerTest.kt
1
1657
package org.example.domain import org.example.domain.query.QContact import org.example.domain.query.QCountry import org.example.domain.query.QCustomer import org.example.domain.query.QOrder import org.junit.Test import java.time.Instant import org.example.domain.query.QCustomer.Companion._alias as c open class CustomerTest { @Test open fun exampleAliasUse() { LoadExampleData().load() val maxWhen: Instant = QContact() .select("max(whenModified)::Instant") .findSingleAttribute() println("got $maxWhen") val con = QContact._alias val customers2 = QCustomer() .select(c.name, c.version, c.whenCreated) .contacts.fetch(con.email) .name.istartsWith("Rob") .findList() val orders = QOrder() //.orderDate.after(LocalDate.MIN) //.status.isIn(Order.Status.APPROVED, Order.Status.COMPLETE) .select(QOrder._alias.orderDate) .customer.fetchLazy(c.name, c.deleted) .findList() println(orders) if (true) { return } val list = QCountry() .name.istartsWith("New") //.notes.isNotNull .findList() println(list) val rob = QCustomer() //.codes.isNotEmpty .homeUrl.startsWith("someUrlPrefix") .name.ieq("Rob") .select(c.name)//, cust.version) .findOne() rob?.let { print("hello ${rob.id} ${rob.name}") } val customers = QCustomer() .name.istartsWith("Rob") .billingAddress.country.name.startsWith("New Ze") .or() .deleted.isNotNull .name.isNull .endOr() .findList() println("got customers: $customers") } }
apache-2.0
c399cd0bb2c8ff5fc27121e195a90b11
20.519481
66
0.631865
3.641758
false
false
false
false
TeamWizardry/LibrarianLib
modules/core/src/main/kotlin/com/teamwizardry/librarianlib/math/SimpleCoordinateSpace2D.kt
1
2240
package com.teamwizardry.librarianlib.math import com.teamwizardry.librarianlib.core.util.vec import net.minecraft.util.math.Vec3d public class SimpleCoordinateSpace2D: CoordinateSpace2D { override var parentSpace: CoordinateSpace2D? = null public var pos: Vec2d = vec(0, 0) public var scale2d: Vec2d = vec(1, 1) public var scale: Double get() = (scale2d.x + scale2d.y) / 2 set(value) { scale2d = vec(value, value) } public var rotation: Double = 0.0 override var transform: Matrix3d = Matrix3d.IDENTITY get() { updateMatrixIfNeeded() return field } private set override var inverseTransform: Matrix3d = Matrix3d.IDENTITY get() { updateMatrixIfNeeded() return field } private set private data class MatrixParams(val pos: Vec2d = Vec2d.ZERO, val rotation: Quaternion = Quaternion.IDENTITY, val scale: Vec3d = vec(1, 1, 1), val inverseRotation: Quaternion = Quaternion.IDENTITY, val inverseScale: Vec3d = vec(1, 1, 1)) private var matrixParams = MatrixParams() private fun createMatrix() { val matrix = MutableMatrix3d() matrix.translate(matrixParams.pos) matrix.rotate(matrixParams.rotation) matrix.scale(matrixParams.scale) this.transform = matrix.toImmutable() matrix.set(Matrix3d.IDENTITY) matrix.scale(matrixParams.inverseScale) matrix.rotate(matrixParams.rotation) matrix.translate(-matrixParams.pos) this.inverseTransform = matrix.toImmutable() } private fun updateMatrixIfNeeded() { val inverseScale = vec( if (scale2d.x == 0.0) Double.POSITIVE_INFINITY else 1.0 / scale2d.x, if (scale2d.y == 0.0) Double.POSITIVE_INFINITY else 1.0 / scale2d.y, 1 ) val rotation = Quaternion.fromAngleDegAxis(rotation, 0.0, 1.0, 0.0) val newParams = MatrixParams(pos, rotation, vec(scale2d.x, scale2d.y, 1), rotation.invert(), inverseScale ) if (newParams != matrixParams) { matrixParams = newParams createMatrix() } } }
lgpl-3.0
f3e929c0e2d571e1cb64f0e09c706f0c
31.478261
102
0.625446
3.957597
false
false
false
false
rwinch/spring-security
config/src/main/kotlin/org/springframework/security/config/web/server/ServerLogoutDsl.kt
5
2307
/* * Copyright 2002-2020 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 * * 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 org.springframework.security.config.web.server import org.springframework.security.web.server.authentication.logout.ServerLogoutHandler import org.springframework.security.web.server.authentication.logout.ServerLogoutSuccessHandler import org.springframework.security.web.server.util.matcher.ServerWebExchangeMatcher /** * A Kotlin DSL to configure [ServerHttpSecurity] logout support using idiomatic Kotlin * code. * * @author Eleftheria Stein * @since 5.4 * @property logoutHandler a [ServerLogoutHandler] that is invoked when logout occurs. * @property logoutUrl the URL that triggers logout to occur. * @property requiresLogout the [ServerWebExchangeMatcher] that triggers logout to occur. * @property logoutSuccessHandler the [ServerLogoutSuccessHandler] to use after logout has * occurred. */ @ServerSecurityMarker class ServerLogoutDsl { var logoutHandler: ServerLogoutHandler? = null var logoutUrl: String? = null var requiresLogout: ServerWebExchangeMatcher? = null var logoutSuccessHandler: ServerLogoutSuccessHandler? = null private var disabled = false /** * Disables logout */ fun disable() { disabled = true } internal fun get(): (ServerHttpSecurity.LogoutSpec) -> Unit { return { logout -> logoutHandler?.also { logout.logoutHandler(logoutHandler) } logoutUrl?.also { logout.logoutUrl(logoutUrl) } requiresLogout?.also { logout.requiresLogout(requiresLogout) } logoutSuccessHandler?.also { logout.logoutSuccessHandler(logoutSuccessHandler) } if (disabled) { logout.disable() } } } }
apache-2.0
753b56925650a60e6c546dbfd0fdb18c
36.209677
95
0.727352
4.614
false
false
false
false
klinker24/Android-TextView-LinkBuilder
library/src/main/java/com/klinker/android/link_builder/TouchableSpan.kt
1
4508
/* 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.klinker.android.link_builder import android.content.Context import android.content.res.TypedArray import android.graphics.Color import android.os.Handler import android.text.TextPaint import android.text.style.ClickableSpan import android.util.TypedValue import android.view.View class TouchableSpan(context: Context, private val link: Link) : TouchableBaseSpan() { private var textColor: Int = 0 private var textColorOfHighlightedLink: Int = 0 init { if (link.textColor == 0) { this.textColor = getDefaultColor(context, R.styleable.LinkBuilder_defaultLinkColor) } else { this.textColor = link.textColor } if (link.textColorOfHighlightedLink == 0) { this.textColorOfHighlightedLink = getDefaultColor(context, R.styleable.LinkBuilder_defaultTextColorOfHighlightedLink) // don't use the default of light blue for this color if (this.textColorOfHighlightedLink == Link.DEFAULT_COLOR) { this.textColorOfHighlightedLink = textColor } } else { this.textColorOfHighlightedLink = link.textColorOfHighlightedLink } } /** * Finds the default color for links based on the current theme. * @param context activity * @param index index of attribute to retrieve based on current theme * @return color as an integer */ private fun getDefaultColor(context: Context, index: Int): Int { val array = obtainStyledAttrsFromThemeAttr(context, R.attr.linkBuilderStyle, R.styleable.LinkBuilder) val color = array.getColor(index, Link.DEFAULT_COLOR) array.recycle() return color } /** * This TouchableSpan has been clicked. * @param widget TextView containing the touchable span */ override fun onClick(widget: View) { if (link.text != null) { link.clickListener?.onClick(link.text!!) } super.onClick(widget) } /** * This TouchableSpan has been long clicked. * @param widget TextView containing the touchable span */ override fun onLongClick(widget: View) { if (link.text != null) { link.longClickListener?.onLongClick(link.text!!) } super.onLongClick(widget) } /** * Set the alpha for the color based on the alpha factor * @param color original color * @param factor how much we want to scale the alpha to * @return new color with scaled alpha */ fun adjustAlpha(color: Int, factor: Float): Int { val alpha = Math.round(Color.alpha(color) * factor) val red = Color.red(color) val green = Color.green(color) val blue = Color.blue(color) return Color.argb(alpha, red, green, blue) } /** * Draw the links background and set whether or not we want it to be underlined or bold * @param ds the link */ override fun updateDrawState(ds: TextPaint) { super.updateDrawState(ds) ds.isUnderlineText = link.underlined ds.isFakeBoldText = link.bold ds.color = if (isTouched) textColorOfHighlightedLink else textColor ds.bgColor = if (isTouched) adjustAlpha(textColor, link.highlightAlpha) else Color.TRANSPARENT if (link.typeface != null) { ds.typeface = link.typeface } } companion object { private fun obtainStyledAttrsFromThemeAttr(context: Context, themeAttr: Int, styleAttrs: IntArray): TypedArray { // Need to get resource id of style pointed to from the theme attr val outValue = TypedValue() context.theme.resolveAttribute(themeAttr, outValue, true) val styleResId = outValue.resourceId // Now return the values (from styleAttrs) from the style return context.obtainStyledAttributes(styleResId, styleAttrs) } } }
mit
8ce1d4001d8bf6e5d48ebede97a96c2f
33.159091
129
0.663487
4.562753
false
false
false
false
Tvede-dk/CommonsenseAndroidKotlin
app/src/main/kotlin/csense/android/exampleApp/fragments/SearchAbleRecyclerDemo.kt
1
3246
package csense.android.exampleApp.fragments import android.support.v7.widget.LinearLayoutManager import android.text.Editable import android.text.TextWatcher import com.commonsense.android.kotlin.base.extensions.collections.repeateToSize import com.commonsense.android.kotlin.views.databinding.adapters.BaseSearchableDataBindingRecyclerAdapter import com.commonsense.android.kotlin.views.databinding.adapters.IRenderModelSearchItem import com.commonsense.android.kotlin.views.databinding.fragments.BaseDatabindingFragment import com.commonsense.android.kotlin.views.databinding.fragments.InflateBinding import com.commonsense.android.kotlin.views.extensions.setOnclickAsync import com.commonsense.android.kotlin.views.extensions.setup import csense.android.exampleApp.databinding.DemoRecyclerSearchableBinding import csense.android.exampleApp.databinding.SimpleListItemBinding /** * Created by kasper on 01/06/2017. */ class SearchAbleSimpleListItemRender(item: String) : SimpleListItemRender(item, 0, {}), IRenderModelSearchItem<String, SimpleListItemBinding, String> { override fun isAcceptedByFilter(value: String): Boolean = item.contains(value) } class SearchAbleRecyclerDemo : BaseDatabindingFragment<DemoRecyclerSearchableBinding>() { override fun getInflater(): InflateBinding<DemoRecyclerSearchableBinding> = DemoRecyclerSearchableBinding::inflate private val adapter by lazy { context?.let { BaseSearchableDataBindingRecyclerAdapter<String>(it) } } override fun useBinding() { val adapter = adapter ?: return val items = mutableListOf<IRenderModelSearchItem<*, *, String>>( SearchAbleSimpleListItemRender("First []"), // SimpleListImageItemRender(Color.BLUE, 0).toSearchable { _, _ -> false }, SearchAbleSimpleListItemRender("Whats up "), // SimpleListImageItemRender(Color.RED, 0).toSearchable { _, _ -> false } ).repeateToSize(2) // adapter.setSection(items, 0) binding.demoRecyclerSearchableRecyclerview.recyclerView.setup(adapter, LinearLayoutManager(context)) // binding.demoRecyclerSearchableRecyclerview2.recyclerView.setup(adapter, LinearLayoutManager(context)) binding.resetButton.setOnclickAsync { adapter.setSection(listOf(), 0) adapter.filterBy("First") adapter.setSection(items, 0) adapter.filterBy("") } binding.demoRecyclerSearchableEdit.addTextChangedListener(SafeTextWatcher(this::performFilter)) } fun performFilter(s: Editable) { val adapter = adapter ?: return val temp = s.toString() if (temp.isEmpty()) { adapter.removeFilter() } else { adapter.filterBy(temp) } } } class SafeTextWatcher(private val onAfterTextChanged: (Editable) -> Unit) : TextWatcher { override fun afterTextChanged(afterChanged: Editable?) { if (afterChanged != null) { this.onAfterTextChanged(afterChanged) } } override fun beforeTextChanged(changedText: CharSequence?, p1: Int, p2: Int, p3: Int) { } override fun onTextChanged(afterChanged: CharSequence?, p1: Int, p2: Int, p3: Int) { } }
mit
7b34ddd8dcb4a25126f4c4c73e1e2d5c
40.101266
151
0.729513
4.571831
false
false
false
false
BrianErikson/PushLocal-Android
PushLocal/src/main/java/com/beariksonstudios/automatic/pushlocal/pushlocal/activities/main/AccessibilityService.kt
1
1214
package com.beariksonstudios.automatic.pushlocal.pushlocal.activities.main import android.app.Notification import android.content.Intent import android.os.Parcelable import android.provider.SyncStateContract import android.util.Log import android.view.accessibility.AccessibilityEvent /** * Created by nphel on 11/8/2015. */ class AccessibilityService : android.accessibilityservice.AccessibilityService() { override fun onAccessibilityEvent(event: AccessibilityEvent) { val eventType = event.eventType if (eventType == AccessibilityEvent.TYPE_NOTIFICATION_STATE_CHANGED) { val sourcePackageName = event.packageName as String val parcelable = event.parcelableData if (parcelable is Notification) { // Statusbar Notification //Log.e(TAG, "Notification -> notification.tickerText :: " + notification.tickerText); val messages = event.text Log.d("Push Local", messages.toString()) Log.d("Push Local", parcelable.tickerText.toString()) } } else { //Log.v(TAG, "Got un-handled Event"); } } override fun onInterrupt() { } }
apache-2.0
839814c41509960cec62daa54e77dc33
32.722222
102
0.667216
4.81746
false
false
false
false
android/views-widgets-samples
ConstraintLayoutExamples/motionlayout/src/main/java/com/google/androidstudio/motionlayoutexample/MainActivity.kt
1
6602
package com.google.androidstudio.motionlayoutexample import android.content.Intent import android.os.Bundle import android.widget.CompoundButton import androidx.appcompat.app.AppCompatActivity import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.google.androidstudio.motionlayoutexample.fragmentsdemo.FragmentExample2Activity import com.google.androidstudio.motionlayoutexample.fragmentsdemo.FragmentExampleActivity import com.google.androidstudio.motionlayoutexample.histogramdemo.HistogramActivity import com.google.androidstudio.motionlayoutexample.viewpagerdemo.ViewPagerActivity import com.google.androidstudio.motionlayoutexample.viewpagerdemo.ViewPagerActivity2 import com.google.androidstudio.motionlayoutexample.youtubedemo.YouTubeDemoActivity import kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity(), CompoundButton.OnCheckedChangeListener { private lateinit var recyclerView: RecyclerView private lateinit var viewAdapter: RecyclerView.Adapter<*> private lateinit var viewManager: RecyclerView.LayoutManager private var doShowPaths = false private val dataset: Array<DemosAdapter.Demo> = arrayOf( DemosAdapter.Demo("Basic Example (1/3)", "Basic motion example using referenced ConstraintLayout files", R.layout.motion_01_basic), DemosAdapter.Demo("Basic Example (2/3)", "Basic motion example using ConstraintSets defined in the MotionScene file", R.layout.motion_02_basic), DemosAdapter.Demo("Basic Example (3/3)", "Basic motion example same as 2, but autoComplete is set to false in onSwipe", R.layout.motion_02_basic_autocomplete_false), DemosAdapter.Demo("Custom Attribute", "Show color interpolation (custom attribute)", R.layout.motion_03_custom_attribute), DemosAdapter.Demo("ImageFilterView (1/2)", "Show image cross-fade (using ML's ImageFilterView + custom attribute)", R.layout.motion_04_imagefilter), DemosAdapter.Demo("ImageFilterView (2/2)", "Show image saturation transition (using ML's ImageFilterView + custom attribute)", R.layout.motion_05_imagefilter), DemosAdapter.Demo("Keyframe Position (1/3)", "Use a simple keyframe to change the interpolated motion", R.layout.motion_06_keyframe), DemosAdapter.Demo("Keyframe Interpolation (2/3)", "More complex keyframe, adding rotation interpolation", R.layout.motion_07_keyframe), DemosAdapter.Demo("Keyframe Cycle (3/3)", "Basic example of using a keyframe cycle ", R.layout.motion_08_cycle), DemosAdapter.Demo("CoordinatorLayout Example (1/3)", "Basic example of using MotionLayout instead of AppBarLayout", R.layout.motion_09_coordinatorlayout), DemosAdapter.Demo("CoordinatorLayout Example (2/3)", "Slightly more complex example of MotionLayout replacing AppBarLayout, with multiple elements and parallax background", R.layout.motion_10_coordinatorlayout), DemosAdapter.Demo("CoordinatorLayout Example (3/3)", "Another AppBarLayout replacement example", R.layout.motion_11_coordinatorlayout), DemosAdapter.Demo("DrawerLayout Example (1/2)", "Basic DrawerLayout with MotionLayout", R.layout.motion_12_drawerlayout), DemosAdapter.Demo("DrawerLayout Example (2/2)", "Advanced DrawerLayout with MotionLayout", R.layout.motion_13_drawerlayout), DemosAdapter.Demo("Side Panel Example", "Side Panel, implemented with MotionLayout only", R.layout.motion_14_side_panel), DemosAdapter.Demo("Parallax Example", "Parallax background. Drag the car.", R.layout.motion_15_parallax), DemosAdapter.Demo("ViewPager Example", "Using MotionLayout with ViewPager", ViewPagerActivity::class.java), DemosAdapter.Demo("ViewPager Lottie Example", "Using MotionLayout and Lottie with ViewPager", ViewPagerActivity2::class.java), DemosAdapter.Demo("Complex Motion Example (1/4)", "Basic CoordinatorLayout-like behavior. Implemented with MotionLayout only, using a moving guideline. Note the view isn't resized. ", R.layout.motion_17_coordination), DemosAdapter.Demo("Complex Motion Example (2/4)", "Advanced CoordinatorLayout-like behavior (adding a FAB). Implemented with MotionLayout only, using a moving guideline. Note the view isn't resized.", R.layout.motion_18_coordination), DemosAdapter.Demo("Complex Motion Example (3/4)", "Advanced CoordinatorLayout-like behavior (adding a FAB). Implemented with MotionLayout only, using direct resizing of the view.", R.layout.motion_19_coordination), DemosAdapter.Demo("Complex Motion Example (4/4)", "Advanced Synchronized reval motion + helper (bounce). Implemented with MotionLayout only.", R.layout.motion_20_reveal), DemosAdapter.Demo("Fragment Transition Example (1/2)", "Example showing transitioning fragments within MotionLayout", FragmentExampleActivity::class.java), DemosAdapter.Demo("Fragment Transition Example (2/2)", "Example showing transitioning fragments within MotionLayout", FragmentExample2Activity::class.java), DemosAdapter.Demo("YouTube like motion Example", "Example showing a transition like YouTube", YouTubeDemoActivity::class.java), DemosAdapter.Demo("Example using KeyTrigger", "Example that calls a method using KeyTrigger", R.layout.motion_25_keytrigger), DemosAdapter.Demo("Example using Multi State", "Example that transitions between multiple states", R.layout.motion_26_multistate), DemosAdapter.Demo("Histogram Example", "Advanced MotionLayout example of creating transition in code and animating dynamic data.", HistogramActivity::class.java) ) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) viewManager = LinearLayoutManager(this) viewAdapter = DemosAdapter(dataset) recyclerView = findViewById<RecyclerView>(R.id.recyclerview).apply { setHasFixedSize(true) layoutManager = viewManager adapter = viewAdapter } showPaths.setOnCheckedChangeListener(this) } override fun onCheckedChanged(p0: CompoundButton?, value: Boolean) { doShowPaths = value } fun start(activity: Class<*>, layoutFileId: Int) { val intent = Intent(this, activity).apply { putExtra("layout_file_id", layoutFileId) putExtra("showPaths", doShowPaths) } startActivity(intent) } }
apache-2.0
09436150286536eafc76a1c2fc22c495
81.525
246
0.749167
4.736011
false
false
false
false
VKCOM/vk-android-sdk
core/src/main/java/com/vk/api/sdk/internal/Validation.kt
1
2170
/******************************************************************************* * The MIT License (MIT) * * Copyright (c) 2019 vk.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. ******************************************************************************/ package com.vk.api.sdk.internal import android.content.Context import android.text.TextUtils object Validation { fun assertContextValid(context: Context?) { if (context == null) throw IllegalArgumentException("context is null") } fun assertCallsPerSecondLimitValid(limit: Int) { if (limit <= 0) throw IllegalArgumentException("Illegal callsPerSecondLimit value: $limit") } fun assertHttpHostValid(host: String?) { if (host == null || host.length == 0) throw IllegalArgumentException("Illegal host value: " + host!!) } fun assertLangValid(lang: String?) { if (TextUtils.isEmpty(lang)) throw IllegalArgumentException("Illegal lang value: " + lang!!) } fun assertAccessTokenValid(accessToken: String?) { if (accessToken == null) throw IllegalArgumentException("Illegal accessToken value") } }
mit
119694eac2e68f12038736d652197a31
42.42
109
0.678341
4.876404
false
false
false
false
moallemi/gradle-advanced-build-version
src/main/kotlin/me/moallemi/gradle/advancedbuildversion/utils/CompatibilityManager.kt
1
2961
/* * Copyright 2020 Reza Moallemi * * 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 me.moallemi.gradle.advancedbuildversion.utils import org.gradle.api.GradleException import org.gradle.api.JavaVersion import org.gradle.api.Project import org.gradle.api.artifacts.Dependency import org.gradle.util.GradleVersion fun checkAndroidGradleVersion(project: Project) { val androidGradlePlugin = getAndroidPlugin(project) if (androidGradlePlugin == null) { throw IllegalStateException( "The Android Gradle plugin not found. " + "gradle-advanced-build-version only works with Android gradle library." ) } else if (!checkAndroidVersion(androidGradlePlugin.version)) { throw GradleException("gradle-advanced-build-version does not support Android Gradle plugin ${androidGradlePlugin.version}") } else if (!project.plugins.hasPlugin("com.android.application")) { throw GradleException("gradle-advanced-build-version only works with android application modules") } } fun checkMinimumGradleVersion() { if (GRADLE_MIN_VERSION > GradleVersion.current()) { throw GradleException("\"gradle-advanced-build-version\" plugin requires at least minimum version $GRADLE_MIN_VERSION. Detected version ${GradleVersion.current()}.") } } fun checkJavaRuntimeVersion() { if (JavaVersion.current() != JavaVersion.VERSION_11) { throw GradleException("\"gradle-advanced-build-version\" plugin requires this build to run with Java 11") } } private fun checkAndroidVersion(version: String?) = listOf("7.").any { version?.startsWith(it) ?: false } fun getAndroidPlugin(project: Project): Dependency? = findClassPathDependencyVersion( project, ANDROID_GRADLE_PLUGIN_GROUP, ANDROID_GRADLE_PLUGIN_ATTRIBUTE_ID ) ?: findClassPathDependencyVersion( project.rootProject, ANDROID_GRADLE_PLUGIN_GROUP, ANDROID_GRADLE_PLUGIN_ATTRIBUTE_ID ) private fun findClassPathDependencyVersion(project: Project, group: String, attributeId: String) = project.buildscript.configurations.getByName("classpath").dependencies.find { group == it.group && it.name == attributeId } internal val GRADLE_MIN_VERSION: GradleVersion = GradleVersion.version("7.0.0") internal const val ANDROID_GRADLE_PLUGIN_GROUP = "com.android.tools.build" internal const val ANDROID_GRADLE_PLUGIN_ATTRIBUTE_ID = "gradle"
apache-2.0
2406f86b1cc1e8bf0d6d585a8fb5fc76
40.125
173
0.734211
4.419403
false
false
false
false
campos20/tnoodle
webscrambles/src/main/kotlin/org/worldcubeassociation/tnoodle/server/webscrambles/zip/model/Folder.kt
1
1057
package org.worldcubeassociation.tnoodle.server.webscrambles.zip.model data class Folder(val name: String, private val rawChildren: List<ZipNode>, val parent: Folder? = null) : AbstractNode(name, parent) { constructor(name: String, parent: Folder? = null) : this(name, emptyList(), parent) val children = rawChildren.map { it.withParent(this) } override fun withParent(parent: Folder) = copy(parent = parent) val allFiles: List<File> get() = flattenFiles(children) operator fun div(childName: String) = Folder(childName, this) operator fun plus(child: ZipNode) = copy(rawChildren = children + child) operator fun plus(moreChildren: List<ZipNode>) = copy(rawChildren = children + moreChildren) companion object { fun flattenFiles(nodes: List<ZipNode>): List<File> { return nodes.flatMap { when (it) { is File -> listOf(it) is Folder -> it.allFiles else -> listOf() } } } } }
gpl-3.0
30d4ee8a6277b196299c9cbbaba2528d
35.448276
134
0.61684
4.262097
false
false
false
false
ShadwLink/Shadow-Mapper
src/main/java/nl/shadowlink/tools/shadowmapper/render/RenderWater.kt
1
1605
package nl.shadowlink.tools.shadowmapper.render import com.jogamp.opengl.GL2 import nl.shadowlink.tools.shadowmapper.FileManager import nl.shadowlink.tools.shadowmapper.gui.PickingType /** * @author Shadow-Link */ class RenderWater( private val fm: FileManager ) { private val waterTex: IntArray? = null fun init() { // TODO: Fix loading water texture // TextureDic WTD = fm.loadWaterTexture(); // waterTex = WTD.textureId; } fun display(gl: GL2) { if (waterTex != null) { //gl.glBindTexture(GL2.GL_TEXTURE_2D, waterTex[0]); drawWater(gl) } } private fun drawWater(gl: GL2) { gl.glPushName(PickingType.water) gl.glBegin(GL2.GL_QUADS) fm.waters[0].planes.forEachIndexed { index, plane -> if (plane.selected) gl.glColor3f(0.9f, 0f, 0f) else gl.glColor4f(0f, 0.4f, 1.0f, 0.5f) val p0 = plane.points[0]!!.coord val p1 = plane.points[1]!!.coord val p2 = plane.points[2]!!.coord val p3 = plane.points[3]!!.coord gl.glPushName(index) gl.glTexCoord2f(plane.u, plane.u) gl.glVertex3f(p0.x, p0.y, p0.z) gl.glTexCoord2f(plane.u, plane.v) gl.glVertex3f(p2.x, p2.y, p2.z) gl.glTexCoord2f(plane.v, plane.v) gl.glVertex3f(p3.x, p3.y, p3.z) gl.glTexCoord2f(plane.v, plane.u) gl.glVertex3f(p1.x, p1.y, p1.z) gl.glPopName() } gl.glEnd() gl.glColor3f(1.0f, 1.0f, 1.0f) gl.glPopName() } }
gpl-2.0
4e2ac20ede1c91b68d76927bc3d94713
29.884615
98
0.572586
2.93956
false
false
false
false
NerdNumber9/TachiyomiEH
app/src/main/java/exh/util/DeferredField.kt
1
990
package exh.util import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock /** * Field that can be initialized later. Users can suspend while waiting for the field to initialize. * * @author nulldev */ class DeferredField<T> { @Volatile private var content: T? = null @Volatile var initialized = false private set private val mutex = Mutex(true) /** * Initialize the field */ fun initialize(content: T) { // Fast-path new listeners this.content = content initialized = true // Notify current listeners mutex.unlock() } /** * Will only suspend if !initialized. */ suspend fun get(): T { // Check if field is initialized and return immediately if it is if(initialized) return content as T // Wait for field to initialize mutex.withLock {} // Field is initialized, return value return content as T } }
apache-2.0
19740cacfbbd9dea214f3bd85fc99c92
20.543478
100
0.619192
4.626168
false
false
false
false
Heiner1/AndroidAPS
app/src/main/java/info/nightscout/androidaps/activities/PreferencesActivity.kt
1
3130
package info.nightscout.androidaps.activities import android.content.Context import android.os.Bundle import android.view.Menu import android.view.MenuItem import androidx.appcompat.widget.SearchView import androidx.preference.PreferenceFragmentCompat import androidx.preference.PreferenceScreen import info.nightscout.androidaps.R import info.nightscout.androidaps.databinding.ActivityPreferencesBinding import info.nightscout.androidaps.utils.locale.LocaleHelper class PreferencesActivity : NoSplashAppCompatActivity(), PreferenceFragmentCompat.OnPreferenceStartScreenCallback { private var preferenceId = 0 private var myPreferenceFragment: MyPreferenceFragment? = null private var searchView: SearchView? = null private lateinit var binding: ActivityPreferencesBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setTheme(R.style.AppTheme) binding = ActivityPreferencesBinding.inflate(layoutInflater) setContentView(binding.root) title = rh.gs(R.string.nav_preferences) supportActionBar?.setDisplayHomeAsUpEnabled(true) supportActionBar?.setDisplayShowHomeEnabled(true) myPreferenceFragment = MyPreferenceFragment() preferenceId = intent.getIntExtra("id", -1) myPreferenceFragment?.arguments = Bundle().also { it.putInt("id", preferenceId) } if (savedInstanceState == null) supportFragmentManager.beginTransaction().replace(R.id.frame_layout, myPreferenceFragment!!).commit() } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.menu_preferences, menu) val searchItem = menu.findItem(R.id.menu_search) searchView = searchItem.actionView as SearchView searchView?.setOnQueryTextListener(object : SearchView.OnQueryTextListener { override fun onQueryTextChange(newText: String): Boolean { myPreferenceFragment?.setFilter(newText) return false } override fun onQueryTextSubmit(query: String): Boolean { return false } }) return super.onCreateOptionsMenu(menu) } override fun onPreferenceStartScreen(caller: PreferenceFragmentCompat, pref: PreferenceScreen): Boolean { val fragment = MyPreferenceFragment() fragment.arguments = Bundle().also { it.putString(PreferenceFragmentCompat.ARG_PREFERENCE_ROOT, pref.key) it.putInt("id", preferenceId) } supportFragmentManager.beginTransaction().replace(R.id.frame_layout, fragment, pref.key).addToBackStack(pref.key).commit() return true } override fun attachBaseContext(newBase: Context) { super.attachBaseContext(LocaleHelper.wrap(newBase)) } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { android.R.id.home -> { onBackPressed() return true } } return super.onOptionsItemSelected(item) } }
agpl-3.0
5b95c702fc4776c63b1fbe8dd63c2059
37.654321
130
0.703834
5.472028
false
false
false
false
sirixdb/sirix
bundles/sirix-rest-api/src/main/kotlin/org/sirix/rest/crud/json/JsonGet.kt
1
15647
package org.sirix.rest.crud.json import io.vertx.core.Context import io.vertx.core.Promise import io.vertx.core.http.HttpHeaders import io.vertx.core.json.JsonObject import io.vertx.ext.auth.User import io.vertx.ext.auth.authorization.AuthorizationProvider import io.vertx.ext.auth.oauth2.OAuth2Auth import io.vertx.ext.web.Route import io.vertx.ext.web.RoutingContext import io.vertx.kotlin.coroutines.await import org.sirix.access.Databases import org.sirix.api.Database import org.sirix.api.json.JsonResourceSession import org.sirix.rest.crud.PermissionCheckingXQuery import org.sirix.rest.crud.QuerySerializer import org.sirix.rest.crud.Revisions import org.sirix.rest.crud.xml.XmlSessionDBStore import org.sirix.service.json.serialize.JsonRecordSerializer import org.sirix.service.json.serialize.JsonSerializer import org.sirix.xquery.JsonDBSerializer import org.sirix.xquery.SirixCompileChain import org.sirix.xquery.SirixQueryContext import org.sirix.xquery.json.* import org.sirix.xquery.node.BasicXmlDBStore import java.io.StringWriter import java.nio.file.Path class JsonGet(private val location: Path, private val keycloak: OAuth2Auth, private val authz: AuthorizationProvider) { suspend fun handle(ctx: RoutingContext): Route { val context = ctx.vertx().orCreateContext val databaseName = ctx.pathParam("database") val resource = ctx.pathParam("resource") val jsonBody = ctx.bodyAsJson val query: String? = ctx.queryParam("query").getOrElse(0) { jsonBody?.getString("query") } get(databaseName, ctx, resource, query, context, ctx.get("user") as User, jsonBody) return ctx.currentRoute() } private suspend fun get( databaseName: String, ctx: RoutingContext, resource: String?, query: String?, vertxContext: Context, user: User, jsonBody: JsonObject? ) { val revision: String? = ctx.queryParam("revision").getOrNull(0) val revisionTimestamp: String? = ctx.queryParam("revision-timestamp").getOrNull(0) val startRevision: String? = ctx.queryParam("start-revision").getOrNull(0) val endRevision: String? = ctx.queryParam("end-revision").getOrNull(0) val startRevisionTimestamp: String? = ctx.queryParam("start-revision-timestamp").getOrNull(0) val endRevisionTimestamp: String? = ctx.queryParam("end-revision-timestamp").getOrNull(0) val nodeId: String? = ctx.queryParam("nodeId").getOrNull(0) var body: String? val database = Databases.openJsonDatabase(location.resolve(databaseName)) database.use { val manager = database.beginResourceSession(resource) manager.use { body = if (query != null && query.isNotEmpty()) { queryResource( databaseName, database, revision, revisionTimestamp, manager, ctx, nodeId, query, vertxContext, user, jsonBody ) } else { val revisions: IntArray = Revisions.getRevisionsToSerialize( startRevision, endRevision, startRevisionTimestamp, endRevisionTimestamp, manager, revision, revisionTimestamp ) serializeResource(manager, revisions, nodeId?.toLongOrNull(), ctx, vertxContext) } } } if (body != null) { ctx.response().end(body) } else { ctx.response().end() } } private suspend fun queryResource( databaseName: String?, database: Database<JsonResourceSession>, revision: String?, revisionTimestamp: String?, manager: JsonResourceSession, ctx: RoutingContext, nodeId: String?, query: String, vertxContext: Context, user: User, jsonBody: JsonObject? ): String? { val dbCollection = JsonDBCollection(databaseName, database) dbCollection.use { val revisionNumber = Revisions.getRevisionNumber(revision, revisionTimestamp, manager) val startResultSeqIndex = ctx.queryParam("startResultSeqIndex").getOrElse(0) { null } val endResultSeqIndex = ctx.queryParam("endResultSeqIndex").getOrElse(0) { null } return xquery( manager, dbCollection, nodeId, revisionNumber, query, ctx, vertxContext, user, startResultSeqIndex?.toLong(), endResultSeqIndex?.toLong(), jsonBody ) } } suspend fun xquery( manager: JsonResourceSession?, dbCollection: JsonDBCollection?, nodeId: String?, revisionNumber: IntArray?, query: String, routingContext: RoutingContext, vertxContext: Context, user: User, startResultSeqIndex: Long?, endResultSeqIndex: Long?, jsonBody: JsonObject? ): String? { return vertxContext.executeBlocking { promise: Promise<String> -> // Initialize queryResource context and store. val jsonDBStore = JsonSessionDBStore(routingContext, BasicJsonDBStore.newBuilder().build(), user, authz) val xmlDBStore = XmlSessionDBStore(routingContext, BasicXmlDBStore.newBuilder().build(), user, authz) val commitMessage = routingContext.queryParam("commitMessage").getOrElse(0) { jsonBody?.getString("commitMessage") } val commitTimestampAsString = routingContext.queryParam("commitTimestamp").getOrElse(0) { jsonBody?.getString("commitTimestamp") } val commitTimestamp = if (commitTimestampAsString == null) { null } else { Revisions.parseRevisionTimestamp(commitTimestampAsString).toInstant() } val queryCtx = SirixQueryContext.createWithJsonStoreAndNodeStoreAndCommitStrategy( xmlDBStore, jsonDBStore, SirixQueryContext.CommitStrategy.AUTO, commitMessage, commitTimestamp ) var body: String? = null queryCtx.use { if (manager != null && dbCollection != null && revisionNumber != null) { val rtx = manager.beginNodeReadOnlyTrx(revisionNumber[0]) rtx.use { if (nodeId == null) { rtx.moveToFirstChild() } else { rtx.moveTo(nodeId.toLong()) } val jsonItem = JsonItemFactory().getSequence(rtx, dbCollection) if (jsonItem != null) { queryCtx.contextItem = jsonItem when (jsonItem) { is AbstractJsonDBArray<*> -> { jsonItem.collection.setJsonDBStore(jsonDBStore) jsonDBStore.addDatabase(jsonItem.collection, jsonItem.collection.database) } is JsonDBObject -> { jsonItem.collection.setJsonDBStore(jsonDBStore) jsonDBStore.addDatabase(jsonItem.collection, jsonItem.collection.database) } is AtomicBooleanJsonDBItem -> { jsonItem.collection.setJsonDBStore(jsonDBStore) jsonDBStore.addDatabase(jsonItem.collection, jsonItem.collection.database) } is AtomicStrJsonDBItem -> { jsonItem.collection.setJsonDBStore(jsonDBStore) jsonDBStore.addDatabase(jsonItem.collection, jsonItem.collection.database) } is AtomicNullJsonDBItem -> { jsonItem.collection.setJsonDBStore(jsonDBStore) jsonDBStore.addDatabase(jsonItem.collection, jsonItem.collection.database) } is NumericJsonDBItem -> { jsonItem.collection.setJsonDBStore(jsonDBStore) jsonDBStore.addDatabase(jsonItem.collection, jsonItem.collection.database) } else -> { throw IllegalStateException("Node type not known.") } } } body = query( xmlDBStore, jsonDBStore, startResultSeqIndex, query, queryCtx, endResultSeqIndex, routingContext ) } } else { body = query( xmlDBStore, jsonDBStore, startResultSeqIndex, query, queryCtx, endResultSeqIndex, routingContext ) } } promise.complete(body) }.await() } private fun query( xmlDBStore: XmlSessionDBStore, jsonDBStore: JsonSessionDBStore, startResultSeqIndex: Long?, query: String, queryCtx: SirixQueryContext, endResultSeqIndex: Long?, routingContext: RoutingContext ): String { val out = StringBuilder() executeQueryAndSerialize( routingContext, xmlDBStore, jsonDBStore, out, startResultSeqIndex, query, queryCtx, endResultSeqIndex ) val body = out.toString() routingContext.response().setStatusCode(200) .putHeader(HttpHeaders.CONTENT_TYPE, "application/json") return body } private fun executeQueryAndSerialize( routingContext: RoutingContext, xmlDBStore: XmlSessionDBStore, jsonDBStore: JsonSessionDBStore, out: StringBuilder, startResultSeqIndex: Long?, query: String, queryCtx: SirixQueryContext, endResultSeqIndex: Long? ) { SirixCompileChain.createWithNodeAndJsonStore(xmlDBStore, jsonDBStore).use { sirixCompileChain -> if (startResultSeqIndex == null) { val serializer = JsonDBSerializer(out, false) PermissionCheckingXQuery( sirixCompileChain, query, keycloak, routingContext.get("user"), authz ).prettyPrint().serialize(queryCtx, serializer) } else { QuerySerializer.serializePaginated( sirixCompileChain, query, queryCtx, startResultSeqIndex, endResultSeqIndex, keycloak, authz, routingContext.get("user"), JsonDBSerializer(out, true) ) { serializer, startItem -> serializer.serialize(startItem) } } } } private suspend fun serializeResource( manager: JsonResourceSession, revisions: IntArray, nodeId: Long?, ctx: RoutingContext, vertxContext: Context ): String { val serializedString = vertxContext.executeBlocking { promise: Promise<String> -> val nextTopLevelNodes = ctx.queryParam("nextTopLevelNodes").getOrNull(0)?.toInt() val lastTopLevelNodeKey = ctx.queryParam("lastTopLevelNodeKey").getOrNull(0)?.toLong() val numberOfNodes = ctx.queryParam("numberOfNodes").getOrNull(0)?.toLong() val maxChildren = ctx.queryParam("maxChildren").getOrNull(0)?.toLong() val out = StringWriter() val withMetaData: String? = ctx.queryParam("withMetaData").getOrNull(0) val maxLevel: String? = ctx.queryParam("maxLevel").getOrNull(0) val prettyPrint: String? = ctx.queryParam("prettyPrint").getOrNull(0) if (nextTopLevelNodes == null) { val serializerBuilder = JsonSerializer.newBuilder(manager, out).revisions(revisions) nodeId?.let { serializerBuilder.startNodeKey(nodeId) } if (withMetaData != null) { when (withMetaData) { "nodeKeyAndChildCount" -> serializerBuilder.withNodeKeyAndChildCountMetaData(true) "nodeKey" -> serializerBuilder.withNodeKeyMetaData(true) else -> serializerBuilder.withMetaData(true) } } if (maxLevel != null) { serializerBuilder.maxLevel(maxLevel.toLong()) } if (maxChildren != null) { serializerBuilder.maxChildren(maxChildren.toLong()) } if (prettyPrint != null) { serializerBuilder.prettyPrint() } if (numberOfNodes != null) { serializerBuilder.numberOfNodes(numberOfNodes) } val serializer = serializerBuilder.build() promise.complete(JsonSerializeHelper().serialize(serializer, out, ctx, manager, revisions, nodeId)) } else { val serializerBuilder = JsonRecordSerializer.newBuilder(manager, nextTopLevelNodes, out).revisions(revisions) nodeId?.let { serializerBuilder.startNodeKey(nodeId) } if (withMetaData != null) { when (withMetaData) { "nodeKeyAndChildCount" -> serializerBuilder.withNodeKeyAndChildCountMetaData(true) "nodeKey" -> serializerBuilder.withNodeKeyMetaData(true) else -> serializerBuilder.withMetaData(true) } } if (maxLevel != null) { serializerBuilder.maxLevel(maxLevel.toLong()) } if (maxChildren != null) { serializerBuilder.maxChildren(maxChildren.toLong()) } if (prettyPrint != null) { serializerBuilder.prettyPrint() } if (lastTopLevelNodeKey != null) { serializerBuilder.lastTopLevelNodeKey(lastTopLevelNodeKey) } if (numberOfNodes != null) { serializerBuilder.numberOfNodes(numberOfNodes) } val serializer = serializerBuilder.build() promise.complete(JsonSerializeHelper().serialize(serializer, out, ctx, manager, revisions, nodeId)) } }.await() ctx.response().setStatusCode(200) .putHeader(HttpHeaders.CONTENT_TYPE, "application/json") return serializedString!! } }
bsd-3-clause
03273a2949c6c785dd102182d0e625df
39.32732
119
0.549434
5.401105
false
false
false
false
k9mail/k-9
app/storage/src/main/java/com/fsck/k9/storage/messages/MoveMessageOperations.kt
1
5235
package com.fsck.k9.storage.messages import android.content.ContentValues import android.database.sqlite.SQLiteDatabase import com.fsck.k9.K9 import com.fsck.k9.helper.getIntOrNull import com.fsck.k9.helper.getLongOrNull import com.fsck.k9.helper.getStringOrNull import com.fsck.k9.mailstore.LockableDatabase import java.util.UUID import timber.log.Timber internal class MoveMessageOperations( private val database: LockableDatabase, private val threadMessageOperations: ThreadMessageOperations ) { fun moveMessage(messageId: Long, destinationFolderId: Long): Long { Timber.d("Moving message [ID: $messageId] to folder [ID: $destinationFolderId]") return database.execute(true) { database -> val threadInfo = threadMessageOperations.createOrUpdateParentThreadEntries(database, messageId, destinationFolderId) val destinationMessageId = createMessageEntry(database, messageId, destinationFolderId, threadInfo) threadMessageOperations.createThreadEntryIfNecessary(database, destinationMessageId, threadInfo) convertOriginalMessageEntryToPlaceholderEntry(database, messageId) destinationMessageId } } private fun createMessageEntry( database: SQLiteDatabase, messageId: Long, destinationFolderId: Long, threadInfo: ThreadInfo? ): Long { val destinationUid = K9.LOCAL_UID_PREFIX + UUID.randomUUID().toString() val contentValues = database.query( "messages", arrayOf( "subject", "date", "flags", "sender_list", "to_list", "cc_list", "bcc_list", "reply_to_list", "attachment_count", "internal_date", "message_id", "preview_type", "preview", "mime_type", "normalized_subject_hash", "read", "flagged", "answered", "forwarded", "message_part_id", "encryption_type" ), "id = ?", arrayOf(messageId.toString()), null, null, null ).use { cursor -> if (!cursor.moveToFirst()) { error("Couldn't find local message [ID: $messageId]") } ContentValues().apply { put("uid", destinationUid) put("folder_id", destinationFolderId) put("deleted", 0) put("empty", 0) put("subject", cursor.getStringOrNull("subject")) put("date", cursor.getLongOrNull("date")) put("flags", cursor.getStringOrNull("flags")) put("sender_list", cursor.getStringOrNull("sender_list")) put("to_list", cursor.getStringOrNull("to_list")) put("cc_list", cursor.getStringOrNull("cc_list")) put("bcc_list", cursor.getStringOrNull("bcc_list")) put("reply_to_list", cursor.getStringOrNull("reply_to_list")) put("attachment_count", cursor.getIntOrNull("attachment_count")) put("internal_date", cursor.getLongOrNull("internal_date")) put("message_id", cursor.getStringOrNull("message_id")) put("preview_type", cursor.getStringOrNull("preview_type")) put("preview", cursor.getStringOrNull("preview")) put("mime_type", cursor.getStringOrNull("mime_type")) put("normalized_subject_hash", cursor.getLongOrNull("normalized_subject_hash")) put("read", cursor.getIntOrNull("read")) put("flagged", cursor.getIntOrNull("flagged")) put("answered", cursor.getIntOrNull("answered")) put("forwarded", cursor.getIntOrNull("forwarded")) put("message_part_id", cursor.getLongOrNull("message_part_id")) put("encryption_type", cursor.getStringOrNull("encryption_type")) } } val placeHolderMessageId = threadInfo?.messageId return if (placeHolderMessageId != null) { database.update("messages", contentValues, "id = ?", arrayOf(placeHolderMessageId.toString())) placeHolderMessageId } else { database.insert("messages", null, contentValues) } } private fun convertOriginalMessageEntryToPlaceholderEntry(database: SQLiteDatabase, messageId: Long) { val contentValues = ContentValues().apply { put("deleted", 1) put("empty", 0) put("read", 1) putNull("subject") putNull("date") putNull("flags") putNull("sender_list") putNull("to_list") putNull("cc_list") putNull("bcc_list") putNull("reply_to_list") putNull("attachment_count") putNull("internal_date") put("preview_type", "none") putNull("preview") putNull("mime_type") putNull("normalized_subject_hash") putNull("flagged") putNull("answered") putNull("forwarded") putNull("message_part_id") putNull("encryption_type") } database.update("messages", contentValues, "id = ?", arrayOf(messageId.toString())) } }
apache-2.0
63140553c8905baa2b6f93c2807f1e29
42.264463
128
0.599618
4.811581
false
false
false
false
k9mail/k-9
app/ui/legacy/src/main/java/com/fsck/k9/contacts/ContactImage.kt
2
1757
package com.fsck.k9.contacts import com.bumptech.glide.load.Key import com.fsck.k9.mail.Address import java.security.MessageDigest /** * Contains all information necessary for [ContactImageBitmapDecoder] to load the contact picture in the desired format. */ class ContactImage( val contactLetterOnly: Boolean, val backgroundCacheId: String, val contactLetterBitmapCreator: ContactLetterBitmapCreator, val address: Address ) : Key { private val contactLetterSignature = contactLetterBitmapCreator.signatureOf(address) override fun updateDiskCacheKey(messageDigest: MessageDigest) { messageDigest.update(toString().toByteArray(Key.CHARSET)) } override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as ContactImage if (contactLetterOnly != other.contactLetterOnly) return false if (backgroundCacheId != other.backgroundCacheId) return false if (address != other.address) return false if (contactLetterSignature != other.contactLetterSignature) return false return true } override fun hashCode(): Int { var result = contactLetterOnly.hashCode() result = 31 * result + backgroundCacheId.hashCode() result = 31 * result + address.hashCode() result = 31 * result + contactLetterSignature.hashCode() return result } override fun toString(): String { return "ContactImage(" + "contactLetterOnly=$contactLetterOnly, " + "backgroundCacheId='$backgroundCacheId', " + "address=$address, " + "contactLetterSignature='$contactLetterSignature'" + ")" } }
apache-2.0
b450470e57ed696ecbe9a2433a10d0b0
32.788462
120
0.682413
4.853591
false
false
false
false
Maccimo/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/RemoveExplicitTypeArgumentsIntention.kt
1
8561
// 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.intentions import com.intellij.codeInspection.LocalQuickFix import com.intellij.codeInspection.ProblemDescriptor import com.intellij.codeInspection.ProblemHighlightType import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.openapi.util.Key import org.jetbrains.kotlin.descriptors.FunctionDescriptor import org.jetbrains.kotlin.descriptors.ValueDescriptor import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyzeInContext import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade import org.jetbrains.kotlin.idea.base.psi.copied import org.jetbrains.kotlin.idea.inspections.IntentionBasedInspection import org.jetbrains.kotlin.idea.project.builtIns import org.jetbrains.kotlin.idea.util.getResolutionScope import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.findDescendantOfType import org.jetbrains.kotlin.psi.psiUtil.getQualifiedExpressionForSelector import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType import org.jetbrains.kotlin.psi.psiUtil.parentsWithSelf import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.DelegatingBindingTrace import org.jetbrains.kotlin.resolve.bindingContextUtil.getDataFlowInfoBefore import org.jetbrains.kotlin.resolve.bindingContextUtil.isUsedAsExpression import org.jetbrains.kotlin.resolve.bindingContextUtil.isUsedAsStatement import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.types.TypeUtils import org.jetbrains.kotlin.types.checker.KotlinTypeChecker @Suppress("DEPRECATION") class RemoveExplicitTypeArgumentsInspection : IntentionBasedInspection<KtTypeArgumentList>(RemoveExplicitTypeArgumentsIntention::class) { override fun problemHighlightType(element: KtTypeArgumentList): ProblemHighlightType = ProblemHighlightType.LIKE_UNUSED_SYMBOL override fun additionalFixes(element: KtTypeArgumentList): List<LocalQuickFix>? { val declaration = element.getStrictParentOfType<KtCallableDeclaration>() ?: return null if (!RemoveExplicitTypeIntention.isApplicableTo(declaration)) return null return listOf(RemoveExplicitTypeFix(declaration.nameAsSafeName.asString())) } private class RemoveExplicitTypeFix(private val declarationName: String) : LocalQuickFix { override fun getName() = KotlinBundle.message("remove.explicit.type.specification.from.0", declarationName) override fun getFamilyName() = name override fun applyFix(project: Project, descriptor: ProblemDescriptor) { val element = descriptor.psiElement as? KtTypeArgumentList ?: return val declaration = element.getStrictParentOfType<KtCallableDeclaration>() ?: return RemoveExplicitTypeIntention.removeExplicitType(declaration) } } } class RemoveExplicitTypeArgumentsIntention : SelfTargetingOffsetIndependentIntention<KtTypeArgumentList>( KtTypeArgumentList::class.java, KotlinBundle.lazyMessage("remove.explicit.type.arguments") ) { companion object { fun isApplicableTo(element: KtTypeArgumentList, approximateFlexible: Boolean): Boolean { val callExpression = element.parent as? KtCallExpression ?: return false val typeArguments = callExpression.typeArguments if (typeArguments.isEmpty()) return false if (typeArguments.any { it.typeReference?.isAnnotatedDeep() == true }) return false val resolutionFacade = callExpression.getResolutionFacade() val bindingContext = resolutionFacade.analyze(callExpression, BodyResolveMode.PARTIAL_WITH_CFA) val originalCall = callExpression.getResolvedCall(bindingContext) ?: return false val (contextExpression, expectedType) = findContextToAnalyze(callExpression, bindingContext) val resolutionScope = contextExpression.getResolutionScope(bindingContext, resolutionFacade) val key = Key<Unit>("RemoveExplicitTypeArgumentsIntention") callExpression.putCopyableUserData(key, Unit) val expressionToAnalyze = contextExpression.copied() callExpression.putCopyableUserData(key, null) val newCallExpression = expressionToAnalyze.findDescendantOfType<KtCallExpression> { it.getCopyableUserData(key) != null }!! newCallExpression.typeArgumentList!!.delete() val newBindingContext = expressionToAnalyze.analyzeInContext( resolutionScope, contextExpression, trace = DelegatingBindingTrace(bindingContext, "Temporary trace"), dataFlowInfo = bindingContext.getDataFlowInfoBefore(contextExpression), expectedType = expectedType ?: TypeUtils.NO_EXPECTED_TYPE, isStatement = contextExpression.isUsedAsStatement(bindingContext) ) val newCall = newCallExpression.getResolvedCall(newBindingContext) ?: return false val args = originalCall.typeArguments val newArgs = newCall.typeArguments fun equalTypes(type1: KotlinType, type2: KotlinType): Boolean { return if (approximateFlexible) { KotlinTypeChecker.DEFAULT.equalTypes(type1, type2) } else { type1 == type2 } } return args.size == newArgs.size && args.values.zip(newArgs.values).all { (argType, newArgType) -> equalTypes(argType, newArgType) } } private fun findContextToAnalyze(expression: KtExpression, bindingContext: BindingContext): Pair<KtExpression, KotlinType?> { for (element in expression.parentsWithSelf) { if (element !is KtExpression) continue if (element.getQualifiedExpressionForSelector() != null) continue if (element is KtFunctionLiteral) continue if (!element.isUsedAsExpression(bindingContext)) return element to null when (val parent = element.parent) { is KtNamedFunction -> { val expectedType = if (element == parent.bodyExpression && !parent.hasBlockBody() && parent.hasDeclaredReturnType()) (bindingContext[BindingContext.DECLARATION_TO_DESCRIPTOR, parent] as? FunctionDescriptor)?.returnType else null return element to expectedType } is KtVariableDeclaration -> { val expectedType = if (element == parent.initializer && parent.typeReference != null) (bindingContext[BindingContext.DECLARATION_TO_DESCRIPTOR, parent] as? ValueDescriptor)?.type else null return element to expectedType } is KtParameter -> { val expectedType = if (element == parent.defaultValue) (bindingContext[BindingContext.DECLARATION_TO_DESCRIPTOR, parent] as? ValueDescriptor)?.type else null return element to expectedType } is KtPropertyAccessor -> { val property = parent.parent as KtProperty val expectedType = when { element != parent.bodyExpression || parent.hasBlockBody() -> null parent.isSetter -> parent.builtIns.unitType property.typeReference == null -> null else -> (bindingContext[BindingContext.DECLARATION_TO_DESCRIPTOR, parent] as? FunctionDescriptor)?.returnType } return element to expectedType } } } return expression to null } } override fun isApplicableTo(element: KtTypeArgumentList): Boolean = isApplicableTo(element, approximateFlexible = false) override fun applyTo(element: KtTypeArgumentList, editor: Editor?) = element.delete() }
apache-2.0
e8c00003df5215b0397b938eec5a09a9
50.890909
140
0.683682
6.136918
false
false
false
false
ligi/PassAndroid
android/src/androidTest/java/org/ligi/passandroid/injections/FixedPassListPassStore.kt
1
1795
package org.ligi.passandroid.injections import kotlinx.coroutines.channels.BroadcastChannel import kotlinx.coroutines.channels.ConflatedBroadcastChannel import org.ligi.passandroid.model.PassClassifier import org.ligi.passandroid.model.PassStore import org.ligi.passandroid.model.PassStoreUpdateEvent import org.ligi.passandroid.model.pass.Pass import java.io.File class FixedPassListPassStore(private var passes: List<Pass>) : PassStore { override lateinit var classifier: PassClassifier init { classifier = PassClassifier(HashMap(), this) } fun setList(newPasses: List<Pass>, newCurrentPass: Pass? = newPasses.firstOrNull()) { currentPass = newCurrentPass passes = newPasses passMap.clear() passMap.putAll(createHashMap()) classifier = PassClassifier(HashMap(), this) } override var currentPass: Pass? = null override val passMap: HashMap<String, Pass> by lazy { return@lazy createHashMap() } private fun createHashMap(): HashMap<String, Pass> { val hashMap = HashMap<String, Pass>() passes.forEach { hashMap[it.id] = it } return hashMap } override fun getPassbookForId(id: String): Pass? { return passMap[id] } override fun deletePassWithId(id: String): Boolean { return false } override fun getPathForID(id: String): File { return File("") } override val updateChannel: BroadcastChannel<PassStoreUpdateEvent> = ConflatedBroadcastChannel() override fun save(pass: Pass) { // no effect in this impl } override fun notifyChange() { // no effect in this impl } override fun syncPassStoreWithClassifier(defaultTopic: String) { // no effect in this impl } }
gpl-3.0
29cae894162c0d380f4e37be54c0ec4a
25.397059
100
0.687465
4.378049
false
false
false
false
fcostaa/kotlin-rxjava-android
feature/wiki/src/main/kotlin/com/github/felipehjcosta/marvelapp/wiki/view/LoadingWikiGalleryCallbacksHandler.kt
1
1356
package com.github.felipehjcosta.marvelapp.wiki.view import android.graphics.drawable.GradientDrawable import android.graphics.drawable.LayerDrawable import android.view.View import android.widget.FrameLayout import com.github.felipehjcosta.layoutmanager.GalleryLayoutManager import com.github.felipehjcosta.marvelapp.base.R class LoadingWikiGalleryCallbacksHandler : GalleryLayoutManager.ItemTransformer { override fun transformItem( layoutManager: GalleryLayoutManager, item: View, viewPosition: Int, fraction: Float ) { item.pivotX = item.width / 2.0f item.pivotY = item.height / 2.0f val scale = 1.0f - SCALE_MULTIPLE * Math.abs(fraction) item.scaleX = scale item.scaleY = scale item.translationX = -item.width / 2.0f + item.resources.getDimensionPixelSize(R.dimen.gallery_item_padding_left) val layerDrawable = (item as FrameLayout).foreground as LayerDrawable val gradient = layerDrawable.getDrawable(0) as GradientDrawable val alphaFraction = 1.0f - Math.abs(fraction) val alpha = WHITE_COLOR_RGB - Math.round(WHITE_COLOR_RGB * alphaFraction) gradient.alpha = alpha } companion object { private const val WHITE_COLOR_RGB = 255 private const val SCALE_MULTIPLE = 0.3f } }
mit
69b4a0d13111fe664080d38b1b9722a2
34.684211
87
0.704277
4.346154
false
false
false
false
nearbydelta/KoreanAnalyzer
core/src/test/kotlin/kr/bydelta/koala/test.kt
1
44136
package kr.bydelta.koala import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.async import kotlinx.coroutines.runBlocking import kr.bydelta.koala.proc.* import org.amshove.kluent.* import org.spekframework.spek2.dsl.GroupBody import org.spekframework.spek2.dsl.Root import org.spekframework.spek2.lifecycle.CachingMode import org.spekframework.spek2.style.specification.Suite import org.spekframework.spek2.style.specification.describe import java.util.* /** * 테스트용 예제를 제공하는 인터페이스. */ object Examples { fun exampleSequence(duplicate: Int = 1, requireMultiLine: Boolean = false): List<Pair<Int, String>> { val seq = if (requireMultiLine) exampleSeq.filter { it.first > 1 } else exampleSeq return (0 until duplicate).flatMap { seq }.shuffled().toList() } private val examples = listOf( """01 1+1은 2이고, 3*3은 9이다. |01 RHINO는 말줄임표를... 확인해야함... ^^ 이것도 확인해야. |03 식사함은 식사에서부터인지 식사에서부터이었는지 살펴봄. 보기에는 살펴봄이 아리랑을 위한 시험임을 지나쳤음에. 사랑하였음은 사랑해봄은 보고싶기에 써보기에 써보았기에. |03 먹음이니. 먹음이었으니. 사면되어보았기에. |01 a/b는 분수이다. |01 가가간 가가 가가가 가가? |01 | 기호는 분리기호이다. |02 ▶ 오늘의 날씨입니다. ◆ 기온 23도는 낮부터임. |01 【그】가 졸음이다. 사랑스러웠기에. |01 [Dr.브레인 - 마루투자자문 조인갑 대표] |01 [결 마감특징주 - 유진투자증권 갤러리아지점 나현진 대리] |01 진경복 한기대 산학협력단장은 "이번 협약 체결로 우수한 현장 기능 인력에 대한 대기업-중소기업간 수급 불균형 문제와 중소·중견기업들에 대한 취업 기피 현상을 해결할 것"이라며 "특성화 및 마이스터고 학생들을 대학에 진학시켜 자기계발 기회를 제공하는 국내 최초의 상생협력 모델이라는 점에 의미가 있다"고 강조했다. |01 [결 마감특징주 - 신한금융투자 명품PB강남센터 남경표 대리] |01 [Dr.브레인 - 마루투자자문 조인갑 대표] |01 '플라이 아웃'은 타자가 친 공이 땅에 닿기 전에 상대팀 야수(투수와 포수를 제외한 야수들-1·2·3루수, 좌익수, 중견수, 우익수, 유격수)가 잡는 것, '삼진 아웃'은 스트라이크가 세 개가 되어 아웃되는 것을 말한다. |01 대선 출마를 선언한 민주통합당 손학규 상임고문이 5일 오후 서울 세종문화회관 세종홀에서 열린 '저녁이 있는 삶-손학규의 민생경제론'출판기념회에서 행사장으로 들어서며 손을 들어 인사하고 있다.2012.7.5/뉴스1""".trimMargin(), // Example 1: JTBC, 2017.04.22 """03 북한이 도발을 멈추지 않으면 미국이 북핵 시설을 타격해도 군사개입을 하지 않겠다. 중국 관영 환구시보가 밝힌 내용인데요. 중국이 여태껏 제시한 북한에 대한 압박 수단 가운데 가장 이례적이고, 수위가 높은 것으로 보입니다. |01 이한주 기자입니다. |02 중국 관영매체 환구시보가 북핵문제에 대해 제시한 중국의 마지노선입니다. 북핵 억제를 위해 외교적 노력이 우선해야 하지만 북한이 도발을 지속하면 핵시설 타격은 용인할 수 있다는 뜻을 내비친 겁니다. |02 그러나 한국과 미국이 38선을 넘어 북한 정권 전복에 나서면 중국이 즉각 군사개입에 나서야 한다는 점을 분명히 하였습니다. 북한에 대한 압박수위도 한층 높였습니다. |02 핵실험을 강행하면 트럼프 대통령이 북한의 생명줄로 지칭한 중국의 원유공급을 대폭 축소할 거라고 경고하였습니다. 축소 규모에 대해서도 '인도주의적 재앙이 일어나지 않는 수준'이라는 기준까지 제시하며 안보리 결정을 따르겠다고 못 박았습니다. |02 중국 관영매체가 그동안 북한에 자제를 요구한 적은 있지만, 군사지원 의무제공 포기 가능성과 함께 유엔 안보리 제재안을 먼저 제시한 것은 이례적입니다. 미·중 빅딜에 따른 대북압박 공조 가능성이 제기되는 가운데 북한이 어떤 반응을 보일지 관심이 쏠립니다.""".trimMargin(), // Example2: 한국대학신문, 17.04.21 """01 홍준표 '돼지흥분제 논란' 일파만파…사퇴 요구 잇달아(종합) |01 2005년 자서전서 성범죄 모의 내용 뒤늦게 알려져 |01 "혈기왕성할 때" 한국당 해명도 빈축…국민의당·바른정당 사퇴 요구 |02 자유한국당 홍준표 대선후보가 대학 시절 약물을 이용한 친구의 성범죄 모의에 가담하였다고 자서전에서 고백한 사실이 21일 뒤늦게 알려지면서 논란이 커지고 있다. 이를 접한 누리꾼들 사이에서 비난 여론이 비등한 상황에서 국민의당과 바른정당 등 정치권에선 홍 후보에게 사퇴를 요구하는 목소리가 나오고 있다. |02 문제가 된 부분은 홍 후보가 한나라당(자유한국당 전신) 의원으로 활동하던 2005년 출간한 자전적 에세이 '나 돌아가고 싶다'의 '돼지 흥분제 이야기' 대목이다. 홍 후보는 고려대 법대 1학년생 때 있었던 일이라면서 "같은 하숙집의 S대 1학년 남학생이 짝사랑하던 여학생을 월미도 야유회 때 자기 사람으로 만들겠다며 하숙집 동료들에게 흥분제를 구해달라고 하였다"고 밝혔다. |02 그는 이어 "우리 하숙집 동료들은 궁리 끝에 흥분제를 구해주기로 하였다"면서 해당 남학생이 맥주에 흥분제를 타서 여학생에게 먹였으나 여학생의 반발로 미수에 그친 점, 하숙집 동료들 간 흥분제 약효를 놓고 격론이 벌어진 점 등을 소개하였다. 이 내용을 발췌한 사진이 사회관계망서비스(SNS)를 타고 본격적으로 퍼지면서 인터넷에서는 명백한 성범죄 모의라면서 분노하는 여론이 크게 일었다. |01 이에 홍 후보는 이날 오전 서울 강남구 삼성동 코엑스에서 간담회를 마친 뒤 취재진과 만나 "내가 (성범죄에) 관여한 게 아니다"라고 해명하였다. |01 그는 "같이 하숙하던 S대 학생들이 하는 이야기를 옆에서 들은 것"이라면서 "책의 포맷을 보면 S대 학생들 자기네끼리 한 이야기를 내가 관여한 듯이 해놓고 후회하는 것으로 해야지 정리가 되는 그런 포맷"이라고 주장하였다. |03 하지만 온라인 여론은 싸늘하였다. 홍 후보가 스스로 글의 말미에 '가담'이라고 표현한만큼 "들은 이야기"라는 해명을 사실 그대로 받아들이기 어렵다는 것이다. 홍 후보는 책에 "다시 (과거로) 돌아가면 절대 그런 일에 가담하지 않을 것"이라며 "장난삼아 한 일이지만 그것이 얼마나 큰 잘못인지 검사가 된 후에 비로소 알았다"고 서술하였다. |02 "혈기왕성한 때 벌어진 일"이라는 한국당의 해명도 또다른 논란을 불렀다. 이 당 정준길 대변인은 이날 오전 tbs라디오 인터뷰에서 "당시에도 책에서 이미 잘못된 일이라고 반성하였고 지금 생각해도 잘못된 일"이라면서 "그것이 불쾌하였다면 국민에게 진심으로 사과드린다"고 말하였다. |01 그러면서 "다만 지금으로부터 45년 전, 사회적 분위기가 다른 상황에서 혈기왕성한 대학교 1학년 때 벌어진 일이라는 점을 너그럽게 감안해 주셨으면 좋겠다"고 덧붙여 비판을 샀다. |02 다른 당에서는 홍 후보에게 후보직 사퇴를 요구하면서 여론전에 나섰다. 국민의당 안철수 후보 측은 "홍 후보가 대학 시절 강간미수의 공동정범이었다는 사실이 재조명되었다"고 지적하면서 후보직 사퇴를 요구하였다. |01 국민의당 선거대책위 김경록 대변인은 논평을 통해 "대학교 1학년생에게 약물을 몰래 먹인 성폭력의 공범임이 드러난 이상 우리는 홍 후보를 대선 후보로 인정할 수 없다"면서 "한국당의 유일한 여성 공동선대위원장인 나경원 의원이 나서 홍 후보 자격을 박탈하라"고 요구하였다. |02 바른정당도 "여성에 저급한 인식을 보여준다"며 가세하였다. 유승민 대선후보는 이날 오전 여의도 서울마리나클럽에서 열린 한국방송기자클럽 대선후보 초청토론회에서 "충격적인 뉴스다. 이런 사람이 어떻게 대선 후보가 될 수 있느냐"고 목소리를 높였다. |01 바른당의 박순자·박인숙·이혜훈·이은재·진수희·김을동 등 전현직 여성 의원 10명도 이날 오후 국회 정론관 기자회견을 통해 홍 후보를 규탄하였다. |01 이들은 "현역 국회의원인 시점에 자서전을 내면서 부끄러운 범죄사실을 버젓이 써놓고 사과 한마디 없다는 것은 더 기막히다"라면서 "대선후보가 아닌 정상적인 사고를 가진 한 인간으로서도 자질부족인 홍 후보의 사퇴를 촉구한다"고 밝혔다.""".trimMargin(), // Example 3. 허핑턴포스트, 17.04.22 """01 박근혜 전 대통령이 거주하던 서울 삼성동 자택은 홍성열 마리오아울렛 회장(63)이 67억5000만원에 매입한 것으로 확인되었다. |01 홍 회장은 21일 뉴스1과의 통화에서 "값이 싸게 나오고 위치가 좋아서 삼성동 자택을 사게 되었다"고 밝혔다. |01 홍 회장은 "제가 강남에 집이나 땅이 하나도 없어서 알아보던 중에 부동산에 아는 사람을 통해서 삼성동 자택이 매물로 나온 걸 알게 되었다"며 "처음에는 조금 부담되었지만 집사람도 크게 문제가 없다고 해서 매입하였다"고 말하였다. |01 이어 "조만간 이사를 할 생각이지만 난방이나 이런게 다 망가졌다기에 보고나서 이사를 하려한다"며 "집부터 먼저 봐야될 것 같다"고 하였다. |01 홍 회장은 한때 자택 앞에서 박 전 대통령 지지자들의 집회로 주민들이 큰 불편을 겪었던 것과 관련 "주인이 바뀌면 그런 일을 할 이유가 없을 것이라 생각한다"고 밝혔다. |01 박 전 대통령과의 인연 등에 대해선 "정치에 전혀 관심이 없고 그런(인연) 건 전혀 없다"며 "박 전 대통령 측이나 친박계 의원 측과의 접촉도 전혀 없었다"고 전하였다. |01 홍 회장은 일부 언론보도로 알려진 박지만 EG회장과의 친분설도 "사실과 다르다"며 "박 전 대통령 사돈의 팔촌과도 인연이 없다"고 거듭 강조하였다. |02 홍 회장에 따르면 자택 매입가는 67억5000만원이다. 홍 회장은 주택을 매입하면서 2억3600만원의 취득세를 납부하였다고 밝혔다. |01 홍 회장은 1980년 마리오상사를 설립한 뒤 2001년 마리오아울렛을 오픈하며 의류 판매업 등으로 국내 최대급 아울렛으로 성장시켰다. |01 한편 박 전 대통령은 최근 삼성동 자택을 매각하고 내곡동에 새 집을 장만한 것으로 확인되었으며 이달 중 내곡동으로 이삿짐을 옮길 것으로 알려졌다.""".trimMargin(), // Example 4. 블로터, 17.08.18 """03 데이터는 미래의 먹거리다. 데이터는 끊임없이 생성되고 변화를 겪기도 한다. 많은 양의 데이터가 생기면서 이를 저장·관리하는 문제부터 어떻게 분석하고 사용하며 어떻게 이를 지켜 내야 하는지 다양한 고민도 함께 등장했다. |03 씨게이트 테크놀로지는 8월17일 열린 '씨게이트 데이터 토론회'에서 '데이터 에이지 2025' 백서를 발표했다. 시장조사기관 IDC 도움을 받아 조사했다. 이날 토론회에는 테 반셍 씨게이트 글로벌 세일즈 수석 부사장, 김수경 IDC코리아 부사장, 김의만 SAP코리아 상무가 참석해 데이터 미래에 관해 이야기를 나눴다. |01 데이터 생산 주체 '소비자' → '기업'으로 |02 '데이터 에이지 2025' 백서에 따르면, 지난 20년 동안 디스크드라이브 업계가 출하한 하드디스크드라이브(HDD)는 80억개로, 용량은 약 4 제타바이트(ZB)에 이른다. 데이터 용량은 점점 늘어나 2025년에는 지금의 10배에 달하는 163 ZB가 생성될 전망이다. |04 1 ZB는 10해 바이트다. 풀어쓰면 '1,000,000,000,000,000,000,000 바이트'로 0이 무려 21개나 붙는다. 또, 1 ZB에 3 MB 안팎의 MP3 음악파일 281조5천억곡을 저장할 수 있다는 점에서, 163 ZB는 실로 어마어마한 규모다. 그러나 이런 데이터가 불과 8년 뒤, 머지않은 미래에 생성된다. |05 단순히 데이터 양만 늘어나고 있는 건 아니다. 데이터를 생산하는 주체도 변화중이다. 기존 20~30년간 상당수 데이터 생산 주체는 소비자였다. 소비자 대부분이 카메라, 모바일, 영상 등에서 데이터를 생산했다. 주로 영화, 음악과 같은 엔터테인먼트 종류 데이터가 많았다. |02 그러나 클라우드로 데이터가 이동하고, 사물인터넷(IoT)이 늘어나면서 기업이나 기계가 데이터를 생산하는 경우가 늘어나고 있다. 씨게이트 측은 2025년에는 전체 데이터의 60% 가량이 기업에 의해 생성될 것으로 분석했다. |01 연결과 새로운 기술, 데이터 증폭을 부르다 |04 8년 뒤, 데이터양이 163 ZB로 늘어나는 데는 몇 가지 원인이 있다. 의료나 항공 등 생명에 연관된 분야에서 사용하는 기기가 늘어난 덕이다. M2M, IoT 기기를 이용한 데이터 수집 사례도 늘어나고 있다는 점도 빼놓을 수 없다. 과거와 다르게 모든 분야에서 데이터를 수집할 수 있는 기회가 늘어남에 따라 행동 자료, 정보 등이 물밀듯 밀려들어 온다. |02 모바일과 실시간 데이터 사용량 증가도 데이터양 증가에 기여한다. 반셍 씨게이트 글로벌 세일즈 수석 부사장은 "2025년이 되면 전세계 인구 75%가 모바일 기기로 연결될 만큼 상당한 모바일 보급이 예상된다"라며 "이 외에 40조 달러 규모의 비즈니스를 차지하는 인공지능과 같은 새로운 코그니티브(인지) 시스템도 삶에 큰 영향을 줄 만큼 데이터를 사용하고 만들어낼 것이며, 이를 위한 보안 문제도 데이터 증폭 환경에 있어 주요 사안이다"라고 설명했다. |01 '엣지 구간'을 주목하라 |02 데이터 처리 과정은 크게 3단계로 이뤄진다. 스마트폰과 PC 등 사용자로부터 바로 데이터를 모으는 '엔드포인트', 이렇게 모은 데이터를 데이터센터로 전달하는 '엣지', 데이터센터에서 데이터를 모아 처리하는 구간인 '코어'로 나뉜다. |02 반셍 수석 부사장은 이 중 엣지 구간을 주목했다. 생성된 정보를 신속하게 분석하고 그에 따라 초 단위 의사 결정이 필요해지면서, 엣지 구간에서 할 일이 많고 중요하다는 이유에서다. |02 많은 양의 데이터가 생기는데 이를 가치 있는 데이터로 만들기 위해서는 분석이 필요합니다. 하지만 신속한 의사결정이 중요시되는 현재인만큼 엔드포인트와 데이터센터 간 거리는 방해 요소가 될 수 있습니다. |01 스토리지의 미래 : 씨게이트 빅데이터 토론회 |02 즉각적인 처리가 중요한 데이터가 늘어난다는 엣지의 개념이 흥미롭다. 엣지에서의 데이터가 어떤 방식으로 늘어나고, 어떤 식으로 처리돼 엔터프라이즈 레벨로 넘어가는가. |08 김의만 SAP코리아 상무(이하 SAP) : SAP에서도 엣지에서 발생하는 데이터 분석, 실시간 의사결정에 관심이 많다. 지난 5월에 열린 SAP 사파이어 컨퍼런스에서 '레오나르도'라는 플랫폼을 발표했다. 이 플랫폼도 엣지 컴퓨팅이 중요 개념으로 꼽았다. 자율주행차도 그렇고, 밀리세컨드로 데이터가 발생하는 공장 설비 같은 부분이 있다. 그런 데이터를 실제 클라우드 플랫폼, 온프레미스로 넘기기는 그 양이 너무나 많다. 또한, 그 양을 모두 수집·분석해 문제 발생에 즉각 대응하기에는 시간이 많이 든다. 그래서 엣지 단에 있는 예측 모델을 기반으로 해서, 실시간 데이터를 기반으로 의사결정을 할 수 있는 시스템을 생각한다. 차후 가장 중요한 데이터, 기업에서 사용되는 중대한 데이터를 실제 데이터 센터로 넘겨서 분석할 수도 있다. |02 지금 발생하는 데이터 중 5% 만이 저장되고 있다고 하는데, 앞으로 데이터는 더 늘어갈 것이다. 이 상황에 데이터 순위를 정해 더 중요하고, 덜 중요한 것으로 처리를 하는 것이 좋을까. |09 테 반셍 씨게이트 글로벌 세일즈 수석 부사장(이하 씨게이트) : 그렇다, 앞으로 데이터는 더 많이 증가할 것이다. 그러나 모두 저장되진 않을것이다. 어떤 데이터를 저장할지에 대해 의사결정을 내리는 것은 앞으로 수년동안 기준을 만들어 결정해야 할 일인듯하다. 지금까지는 비교적 쉽고 간단했다. 그러나 IoT나 M2M(Machine to Machine, 기계간 연결)이 등장하면서 데이터가 더 많아졌다. 하지만 원시데이터 자체를 저장하진 않을 것이다. 그러나 알다시피 분석되지 않는 데이터는 유용하지 않다. AI나 딥러닝과 관련해서 우리가 분석을 원하는 데이터의 양 정보의 양 자체가 훨씬 커질 것이고, 미래에는 데이터 복잡성이 10배 정도 증가할 것이다. 그 많은 데이터 안에서 생활에 아주 큰 영향을 미치는 것들을 분석·저장하고자 할 것이다. |01 인공지능 기술이 발전하면서 데이터의 중요성이 새롭게 밝혀질 수도 있을 듯하다. |03 김수겸 IDC코리아 부사장(이하 IDC) : 데이터 양에 비해 생각하는 것보다 저장해야 하는 데이터는 생각보다 많지 않을 수 있다. 인공지능이 데이터를 분석하더라도 너무 많은 데이터는 확인 후 버리거나 중요한 것에 한해 요약본을 가질 것이다. 중요한 데이터만 기준을 적용한다. |03 많은 데이터를 처리하면서 새로운 정보나 인사이트를 얻을 수도 있지만, 예측하지 못했던 취약점도 나타날 수 있다. 개별적으로 보면 의미가 없던 것이 하나로 합쳐졌을 때 개인 정보일 수도 있듯이 말이다. 이런 취약점에는 어떻게 대응할 수 있을까. |08 씨게이트 : 데이터의 증가로 나타날 수 있는 이슈는 4가지가 있다. 어디에 데이터를 저장할 것인지, 생성된 방대한 데이터를 어떻게 분석할 것인지, 데이터를 엔드포인트에서 코어로 어떻게 이동시킬 것인지, 그리고 마지막으로 데이터의 보안까지. 앞서서 말한 것처럼 전체적으로 보안이 되어야 하는 절반 정도만이 보안 적용돼 있다. 이를 해결하기 위해서는 어디서 데이터를 보호하고 어느 만큼 커버할 것인지 단계별 보완책을 만들어야 한다. 씨게이트는 데이터 센터를 위한 솔루션을 공급하면서 암호화가 가능한 기기가 제공할 수 있지만, 엔드포인트에서 보안 취약점이 남아있을 수도 있다. 이런 부분에서는 솔루션을 우리가 모색을 해야한다. 엔드포인트-엣지-코어로 데이터 이동에도 적용 가능한 보안 점이 필요하고 현재는 부족한 점이 있다. 업계에서 이 부분을 해소해야 할 솔루션에 대한 고민이 필요하다. |02 데이터를 보안 수준에 여러 단계로 나눠서 볼 수도 있다. 그러면 2025년 이후에는 어떤 정도의 보안이 필요할까. |06 IDC : 일단 데이터마다 보안 문제가 다르다. 개인데이터, 규정을 따라야 하는 데이터, 기업 또는 나라의 보안자료 등 다양한 데이터가 있는데, 모든 데이터를 처리할 수는 없다. 많은 논란이 있긴 하지만, 이를 관리하는 주체는 개인보다는 기업과 같은 큰 곳에 맡겨서 관리하는 게 더 중요하다고 본다. 그러니 2025년까지 실질적으로 모든 데이터가 보안이 다 필요하다. 그 역할을 해주는 주체가 기업이 되어야 할 것이고 이 영역에는 많은 투자와 기회가 있다고 생각한다. IDC는 보안이 향후 비즈니스 기회라고 보고 있다. |03 보안이라는 이슈가 기업이나 개인을 위한 보안일 수도 있으나 규제 문제를 일으킬 수도 있다. 브렉시트의 경우 유럽 테크 기업의 길을 바꿀 수 있다는 소리도 나온다. 데이터 보호주의가 엔터프라이즈 데이터 저장에 방해가 되지 않을까. |04 IDC : 더 많은 데이터센터가 생겨 지역 특성에 맞춰 전략을 가지고 공략할 수 있어야 한다. 원하는 곳에서 사업을 하기 위해서는 로컬 영역으로 들어가야 한다. 물리적으로 보기에는 데이터센터에 투자를 하는 게 가치가 있다고 본다. 규제가 있어 장벽이 생기면 또 다른 투자의 기회가 되고, 사업 기회가 될 것이다. |03 씨게이트 : 데이터센터가 늘어날수록 수익창출의 기회가 늘어나는 건 사실이다. 데이터센터가 많아지면 전력, 냉각 문제 등 더 많은 자원을 요구하고 또 다른 문제, 또 다른 도전이 생길 순 있으나, 어떤 도전이든 많은 기회를 의미한다. 업계 차원에서는 이를 낙관적으로 본다. |05 SAP : SAP는 클라우드 퍼스트를 이야기하고, 클라우드를 적극적으로 활용하는 것을 추천한다. 그러나 결론적으로 규제에 따른 제약 같은 부분을 생각하면 각각의 개별기업이 실제 대처하기에는 어려울 수도 있다. 데이터센터를 나라마다 짓기도 어렵다. 각 나라의 클라우드 센터의 애플리케이션 사용하거나 데이터를 저장해 규제나 위반에 대한 위험성를 피해갈수도 있다고 생각한다. 한국에도 클라우드 센터가 많이 지어 지고 있는데, 보호무역주의가 강화되며 클라우드센터와 같은 데이터센터가 늘어날 것이라는 생각이다. |01 데이터 자체가 늘어나면서 기업과 소비자에 각각 어떤 변화가 올 것이며 어떻게 대비를 해야 하는가. |04 SAP : 빅데이터는 IoT나 센서에서 발생하는 많은 데이터에 숨겨진 패턴 찾는 것이 중요하다. 또 한편으로는, 기업들이 가지고 있는 비즈니스 데이터와 빅데이터에서 찾은 데이터를 어떻게 결합하느냐도 중요하다. 어떻게 자신이 가지고 있는 데이터와 결합할 것인지에 대한 비즈니스 시나리오를 고민 해야 한다. 기업고객이 원하는 바와 어떻게 연관시킬 것인가와 연결할 수 있어야 하고, 그런 부분이 종합적으로 고민돼 결과를 도출해야 기업이 향후 영위하는 수익창출에 도움이 될 것이라고 본다. |04 IDC : 기업은 디지털 변혁이 필요하다. 기존에 기반기술(클라우드, 빅데이터, 소셜 비즈니스, 모바일 비즈니스 등)을 바탕으로 AI나 IoT, 로보틱스, 휴먼인터페이스, 3D 페인팅 그리고 이를 다 관장하는 보안 기술까지 모두 중요하다. 앞으로 이런 기술에 맞춰 소비자-기업 관계, 소비자 경험, 생산설비 변경 등 여러 가지가 바뀌어야 한다. 이 같은 환경이 확산되면 디지털 경제가 만들어질 것이다. |11 씨게이트 : 기업 관점에서 보자면 데이터 폭증에 대비해 데이터를 어디에 저장하고, 데이터를 어떻게 분석·처리하며, 데이터를 어떻게 이동하고, 그것을 어떻게 비즈니스에 유용하게 쓰는지에 대해 생각해야 한다. 나아가 이 모든 데이터를 어떻게 보호하느냐 역시 고려해야 한다. 업계의 일원으로서 이런 문제를 봤을 때 당면하는 과제는 결국 어떤 솔루션을 제공해야 이 같은 문제를 극복할 수 있을까로 요약된다. 아직은 엣지 디바이스가 많지는 않지만 앞으로 더 많은 새로운 디바이스가 나올 것이다. 이 상황에 현재 보안은 필요한 만큼의 절반 정도 밖에 충족하지 못하고 있다. 여기서 사업 기회를 찾을 수 있다. 새로운 기회가 될 수 있기에 밝고 낙관적인 전망이 있다고 이야기 하고 싶다. 소비자로서는 모든 것을 통해 혜택을 누릴 수 있다. 생활이 한결 편리해질 것이다. 아무래도 가장 큰 문제는 사생활 문제와 보안이다. 결과적으로 개인은 편안한 삶을 영위하면서도 프라이버시와 보안에 신경을 써야 하고, 기술발전이 어떤 변화를 몰고 올지 역시 생각해야 한다.""".trimMargin()) private val exampleSeq = examples.flatMap { set -> set.split("\n").map { it.take(2).toInt() to it.drop(3) } } } /** * 테스트의 순차적 실행을 강제하기 위한 DSL 추가 */ fun GroupBody.describeSequential(description: String, body: Suite.() -> Unit) { group(description, failFast = true, defaultCachingMode = CachingMode.EACH_GROUP, preserveExecutionOrder = true) { body(Suite(this)) } } /** * [CanSplitSentence]를 테스트합니다. */ fun SplitterSpek(getSplitter: () -> CanSplitSentence, originalSplitCounter: (String) -> Int): Root.() -> Unit { return { defaultTimeout = 300000L // 5 minutes describeSequential("SentenceSplitter") { it("handles empty sentence") { val sent = getSplitter().sentences("") sent.size `should be equal to` 0 } it("splits sentences") { Examples.exampleSequence(requireMultiLine = true).forEach { getSplitter().sentences(it.second).size `should be equal to` originalSplitCounter(it.second) } } it("should be thread-safe") { val sents = Examples.exampleSequence(duplicate = 2, requireMultiLine = true) val multiThreaded = runBlocking { sents.map { async(Dispatchers.Default + NonCancellable) { getSplitter()(it.second) } }.flatMap { it.await() } } val splitter = getSplitter() val singleThreaded = sents.flatMap { splitter(it.second) } multiThreaded.zip(singleThreaded).forEach { it.first `should be equal to` it.second } } } } } /** * [CanTag]를 테스트합니다. */ fun TaggerSpek(getTagger: () -> CanTag, tagSentByOrig: (String) -> Pair<String, String>, tagParaByOrig: (String) -> List<String>, tagSentByKoala: (String, CanTag) -> Pair<String, String> = { str, tagger -> val tagged = tagger.tagSentence(str) val tag = tagged.joinToString(" ") { it.joinToString("+") { m -> m.surface + "/" + m.originalTag } } val surface = tagged.surfaceString() surface to tag }, isSentenceSplitterImplemented: Boolean = false, isParagraphImplemented: Boolean = true): Root.() -> Unit { return { defaultTimeout = 300000L // 5 minutes val globalTagger = getTagger() fun expectCorrectParse(str: String) { println("OriginalTag") val (oSurface, oTag) = tagSentByOrig(str) val (tSurface, tTag) = tagSentByKoala(str, globalTagger) if (oTag.isNotEmpty()) tTag `should be equal to` oTag if (oSurface.isNotEmpty()) tSurface `should be equal to` oSurface tSurface.replace("\\s+".toRegex(), "") `should be equal to` str.replace("\\s+".toRegex(), "") } fun expectThreadSafe(str: List<String>) { val single = str.map { tagSentByKoala(it, globalTagger) } val multiInit = runBlocking { str.map { async(Dispatchers.Default) { tagSentByKoala(it, getTagger()) } }.map { println("MultiInitTag") it.await() } } val multiShared = runBlocking { str.map { async(Dispatchers.Default) { tagSentByKoala(it, globalTagger) } }.map { println("SharedThreadTag") it.await() } } single.zip(multiInit).zip(multiShared).forEach { val (x, m2) = it val (s, m1) = x s.first `should be equal to` m1.first s.second `should be equal to` m1.second s.first `should be equal to` m2.first s.second `should be equal to` m2.second } } describeSequential("Tagger") { it("handles empty sentence") { val sent = globalTagger.tag("") sent.size `should be equal to` 0 } it("tags a sentence") { Examples.exampleSequence().filter { it.first == 1 }.forEach { expectCorrectParse(it.second) } } it("should be thread-safe") { expectThreadSafe(Examples.exampleSequence().filter { it.first == 1 }.map { it.second }) } when { isSentenceSplitterImplemented -> { it("matches sentence split spec") { Examples.exampleSequence(requireMultiLine = true).forEach { println("SentenceSplit ${it.first} sentence(s)") val splits = globalTagger(it.second) if (splits.size != it.first) { println(" NOTMATCHED " + splits.map { it.singleLineString() }) } splits.size `should be equal to` it.first } } } isParagraphImplemented -> { it("tags paragraphs") { Examples.exampleSequence().forEach { println("ParagraphTag ${it.first} sentence(s)") val splits = globalTagger(it.second) val orig = tagParaByOrig(it.second) splits.size `should be equal to` orig.size splits.joinToString("\n") { s -> s.joinToString(" ") { w -> w.joinToString("+") { it.surface } } } `should be equal to` orig.joinToString("\n") } } } else -> { } } } } } data class Conversion(val tag: String, val toTagger: Boolean = true, val toSejong: Boolean = true) /** * 세종 태그 변환을 테스트합니다. */ fun TagConversionSpek(from: (String?) -> POS, to: (POS) -> String, getMapping: (POS) -> List<Conversion>): Root.() -> Unit { return { describe("TagConversion") { it("converts tags correctly") { POS.values().forEach { iPOS -> getMapping(iPOS).forEach { val (tag, toTagger, toSejong) = it if (toTagger) to(iPOS) `should be equal to` tag if (toSejong) from(tag) `should equal` iPOS } } from(null) `should be` POS.NA } } } } /** * [CanCompileDict]를 테스트합니다. */ fun DictSpek(dict: CanCompileDict, getTagger: () -> CanTag, verbOn: Boolean = true, modifierOn: Boolean = true, importFilter: (POS) -> Boolean = { true }): Root.() -> Unit { return { defaultTimeout = 300000L // 5 minutes describeSequential("Dictionary") { it("adds a noun") { { dict.addUserDictionary("갑질", POS.NNG) } `should not throw` AnyException dict.getNotExists(false, "갑질" to POS.NNG).size `should be equal to` 0 dict.getNotExists(false, "갑질" to POS.VX).size `should be greater than` 0 } if (verbOn) { it("adds a verb") { { dict.addUserDictionary("구글링", POS.VV) } `should not throw` AnyException dict.getNotExists(false, "구글링" to POS.VV).size `should be equal to` 0 dict.getNotExists(false, "구글링" to POS.MM).size `should be greater than` 0 } } if (modifierOn) { it("adds a modifier") { { dict.addUserDictionary("대애박", POS.MM) } `should not throw` AnyException dict.getNotExists(false, "대애박" to POS.MM).size `should be equal to` 0 dict.getNotExists(false, "대애박" to POS.NNP).size `should be greater than` 0 } } // getItems, getBaseEntries, getNotExists: Abstract (depends on the actual implementation) it("extracts its system dictionary") { { dict.getBaseEntries { it.isNoun() } } `should not throw` AnyException { dict.getBaseEntries { it.isPredicate() } } `should not throw` AnyException { dict.getBaseEntries { it.isModifier() } } `should not throw` AnyException val nvms = dict.getBaseEntries { it.isNoun() && importFilter(it) }.asSequence().toList() val rand = Random() (0..1000).forEach { if (it % 100 == 0) println("TestSystemDict $it/1000") val entry = nvms[rand.nextInt(nvms.size)] val (surface, pos) = entry dict.contains(surface, setOf(pos)) `should be` true dict.getNotExists(true, entry).isEmpty() `should be` true } } it("should provide way to access user-generated items") { val targets = listOf("테팔코리아" to POS.NNP, "구글코리아" to POS.NNP, "오라클코리아" to POS.NNP, "엔비디아" to POS.NNP, "마이크로소프트" to POS.NNP, "구글하" to POS.VV, "대애박" to POS.IC, "대애박" to POS.MM, "김종국" to POS.NNP, "지나" to POS.VV, "AligatorSky" to POS.NNP).filter { importFilter(it.second) }.toTypedArray() val itemsNotExist = dict.getNotExists(true, *targets) itemsNotExist.forEachIndexed { index, pair -> when (index % 4) { 0 -> { { dict.addUserDictionary(pair) } `should not throw` AnyException } 1 -> { { dict.addUserDictionary(pair.first, pair.second) } `should not throw` AnyException } 2 -> { { dict.addUserDictionary(listOf(pair.first), listOf(pair.second)) } `should not throw` AnyException } else -> { { dict += pair } `should not throw` AnyException } } } targets.forEach { println("Userdic Testing") dict.contains(it.first, setOf(it.second)) `should be` true ((it.first to it.second) in dict) `should be` true } dict.getItems() `should contain all` itemsNotExist } val dictSample = object : CanCompileDict { val words = listOf("마이크로소프트" to POS.NNP, "베지밀" to POS.NNP, "크롬캐스트" to POS.NNP, "하트비트" to POS.NNP).filter { importFilter(it.second) }.toMutableSet() override fun addUserDictionary(vararg dict: Pair<String, POS>) { words.addAll(dict) } override fun getItems(): Set<DicEntry> { return words.toSet() } override fun getBaseEntries(filter: (POS) -> Boolean): Iterator<DicEntry> { return words.filter { filter(it.second) }.listIterator() } override fun getNotExists(onlySystemDic: Boolean, vararg word: DicEntry): Array<DicEntry> { return word.toSet().subtract(this.words).toTypedArray() } } // importFrom it("import from other dictionary") { val itemNotExists = dict.getNotExists(true, *dictSample.words.toTypedArray()) val tagger = getTagger() val sentenceItems = itemNotExists.filter { if (it.second.isNoun()) { val sentence = "우리가 가진 ${it.first}, 그것이 해답이었다." val tagged = tagger.tagSentence(sentence) tagged[2][0].surface != it.first || tagged[2][0].tag != it.second } else false } dict.importFrom(dictSample) dict.getItems() `should contain all` itemNotExists dictSample.words.forEach { println("Import Testing") dict.contains(it.first, setOf(it.second)) `should be` true ((it.first to it.second) in dict) `should be` true }; { sentenceItems.forEach { val sentence = "우리가 가진 ${it.first}, 그것이 해답이었다." tagger.tagSentence(sentence) } } `should not throw` AnyException } } } } /** * [kr.bydelta.koala.proc.CanAnalyzeProperty]를 테스트합니다. */ fun <O, P : CanAnalyzeProperty<O>> ParserSpek(getParser: () -> P, parseSentByOrig: (String) -> List<Pair<String, String>>, parseSentByKoala: (String, P) -> List<Pair<String, String>>): Root.() -> Unit { return { defaultTimeout = 300000L // 5 minutes val globalParser = getParser() fun expectCorrectParse(str: String) { println("OriginalParse") parseSentByOrig(str).zip(parseSentByKoala(str, globalParser)).map { val (oSurface, oTag) = it.first val (tSurface, tTag) = it.second if (oTag.isNotEmpty()) tTag `should be equal to` oTag if (oSurface.isNotEmpty()) tSurface `should be equal to` oSurface } } fun expectThreadSafe(str: List<String>) { val single = str.map { parseSentByKoala(it, globalParser) } val multiInit = runBlocking { str.map { async(Dispatchers.Default) { parseSentByKoala(it, getParser()) } }.map { println("MultiInitParse") it.await() } } val multiShared = runBlocking { str.map { async(Dispatchers.Default) { parseSentByKoala(it, globalParser) } }.map { println("SharedThreadParse") it.await() } } single.zip(multiInit).zip(multiShared).forEach { val (x, m2) = it val (s, m1) = x s.zip(m1).forEach { p -> p.first `should equal` p.second } s.zip(m2).forEach { p -> p.first `should equal` p.second } } } describeSequential("Parser") { it("handles empty sentence") { val sent = globalParser.analyze("") sent.size `should be equal to` 0 } it("parses a string paragraph") { Examples.exampleSequence().forEach { expectCorrectParse(it.second) } } it("parses a sentence instance") { Examples.exampleSequence().filter { it.first == 1 }.forEach { val intermediate = globalParser.convert(it.second)[0].first val sentence = globalParser.convert(intermediate) // Convert 과정에서 기존 tag가 변화될 수 있으므로, Surface만 비교 val directAnalyze = globalParser.analyze(it.second)[0].joinToString(" ") { w -> w.joinToString("+") { m -> m.surface } } val indirectAnalyze = globalParser.analyze(sentence).joinToString(" ") { w -> w.joinToString("+") { m -> m.surface } } directAnalyze `should equal` indirectAnalyze } } it("should be thread-safe") { expectThreadSafe(Examples.exampleSequence().filter { it.first == 1 }.map { it.second }) } } } }
gpl-3.0
ebcc482564521e351a77abe914140abd
50.463793
563
0.538294
2.155869
false
false
false
false
DiUS/pact-jvm
consumer/src/main/kotlin/au/com/dius/pact/consumer/MockHttpServer.kt
1
12124
package au.com.dius.pact.consumer import au.com.dius.pact.consumer.model.MockHttpsProviderConfig import au.com.dius.pact.consumer.model.MockProviderConfig import au.com.dius.pact.consumer.model.MockServerImplementation import au.com.dius.pact.core.matchers.FullRequestMatch import au.com.dius.pact.core.matchers.PartialRequestMatch import au.com.dius.pact.core.matchers.RequestMatching import au.com.dius.pact.core.model.DefaultPactWriter import au.com.dius.pact.core.model.OptionalBody import au.com.dius.pact.core.model.PactSpecVersion import au.com.dius.pact.core.model.Request import au.com.dius.pact.core.model.RequestResponseInteraction import au.com.dius.pact.core.model.RequestResponsePact import au.com.dius.pact.core.model.Response import au.com.dius.pact.core.model.generators.GeneratorTestMode import au.com.dius.pact.core.model.queryStringToMap import au.com.dius.pact.core.support.CustomServiceUnavailableRetryStrategy import com.sun.net.httpserver.Headers import com.sun.net.httpserver.HttpExchange import com.sun.net.httpserver.HttpHandler import com.sun.net.httpserver.HttpServer import com.sun.net.httpserver.HttpsServer import mu.KLogging import org.apache.commons.lang3.StringEscapeUtils import org.apache.http.client.methods.HttpOptions import org.apache.http.config.RegistryBuilder import org.apache.http.conn.socket.ConnectionSocketFactory import org.apache.http.conn.socket.PlainConnectionSocketFactory import org.apache.http.conn.ssl.SSLSocketFactory import org.apache.http.conn.ssl.TrustSelfSignedStrategy import org.apache.http.entity.ContentType import org.apache.http.impl.client.HttpClientBuilder import org.apache.http.impl.conn.BasicHttpClientConnectionManager import java.lang.Thread.sleep import java.nio.charset.Charset import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.ConcurrentLinkedQueue import java.util.zip.DeflaterInputStream import java.util.zip.GZIPInputStream /** * Returns a mock server for the pact and config */ fun mockServer(pact: RequestResponsePact, config: MockProviderConfig): BaseMockServer { return when (config) { is MockHttpsProviderConfig -> when (config.mockServerImplementation) { MockServerImplementation.KTorServer -> KTorMockServer(pact, config) else -> MockHttpsServer(pact, config) } else -> when (config.mockServerImplementation) { MockServerImplementation.KTorServer -> KTorMockServer(pact, config) else -> MockHttpServer(pact, config) } } } interface MockServer { /** * Returns the URL for this mock server. The port will be the one bound by the server. */ fun getUrl(): String /** * Returns the port of the mock server. This will be the port the server is bound to. */ fun getPort(): Int /** * This will start the mock server and execute the test function. Returns the result of running the test. */ fun <R> runAndWritePact(pact: RequestResponsePact, pactVersion: PactSpecVersion, testFn: PactTestRun<R>): PactVerificationResult /** * Returns the results of validating the mock server state */ fun validateMockServerState(testResult: Any?): PactVerificationResult } abstract class AbstractBaseMockServer : MockServer { abstract fun start() abstract fun stop() abstract fun waitForServer() protected fun bodyIsCompressed(encoding: String?): String? { return if (COMPRESSED_ENCODINGS.contains(encoding)) encoding else null } companion object : KLogging() { val COMPRESSED_ENCODINGS = setOf("gzip", "deflate") } } abstract class BaseMockServer(val pact: RequestResponsePact, val config: MockProviderConfig) : AbstractBaseMockServer() { private val mismatchedRequests = ConcurrentHashMap<Request, MutableList<PactVerificationResult>>() private val matchedRequests = ConcurrentLinkedQueue<Request>() private val requestMatcher = RequestMatching(pact.interactions) override fun waitForServer() { val sf = SSLSocketFactory(TrustSelfSignedStrategy()) val retryStrategy = CustomServiceUnavailableRetryStrategy(5, 500) val httpclient = HttpClientBuilder.create() .setConnectionManager(BasicHttpClientConnectionManager(RegistryBuilder.create<ConnectionSocketFactory>() .register("http", PlainConnectionSocketFactory.getSocketFactory()) .register("https", sf) .build())) .setSSLSocketFactory(sf) .setServiceUnavailableRetryStrategy(retryStrategy) .build() val httpOptions = HttpOptions(getUrl()) httpOptions.addHeader("X-PACT-BOOTCHECK", "true") httpclient.execute(httpOptions).close() } override fun <R> runAndWritePact(pact: RequestResponsePact, pactVersion: PactSpecVersion, testFn: PactTestRun<R>): PactVerificationResult { start() waitForServer() val context = PactTestExecutionContext() val testResult: R try { testResult = testFn.run(this, context) sleep(100) // give the mock server some time to have consistent state } catch (e: Throwable) { logger.debug(e) { "Caught exception in mock server" } return PactVerificationResult.Error(e, validateMockServerState(null)) } finally { stop() } return verifyResultAndWritePact(testResult, context, pact, pactVersion) } fun <R> verifyResultAndWritePact( testResult: R, context: PactTestExecutionContext, pact: RequestResponsePact, pactVersion: PactSpecVersion ): PactVerificationResult { val result = validateMockServerState(testResult) if (result is PactVerificationResult.Ok) { val pactDirectory = context.pactFolder val pactFile = pact.fileForPact(pactDirectory) logger.debug { "Writing pact ${pact.consumer.name} -> ${pact.provider.name} to file $pactFile" } DefaultPactWriter.writePact(pactFile, pact, pactVersion) } return result } override fun validateMockServerState(testResult: Any?): PactVerificationResult { if (mismatchedRequests.isNotEmpty()) { return PactVerificationResult.Mismatches(mismatchedRequests.values.flatten()) } val expectedRequests = pact.interactions.asSequence() .map { it.request } .filter { !matchedRequests.contains(it) } .toList() if (expectedRequests.isNotEmpty()) { return PactVerificationResult.ExpectedButNotReceived(expectedRequests) } return PactVerificationResult.Ok(testResult) } protected fun generatePactResponse(request: Request): Response { when (val matchResult = requestMatcher.matchInteraction(request)) { is FullRequestMatch -> { val interaction = matchResult.interaction as RequestResponseInteraction matchedRequests.add(interaction.request) return interaction.response.generatedResponse(emptyMap(), GeneratorTestMode.Consumer) } is PartialRequestMatch -> { val interaction = matchResult.problems.keys.first() as RequestResponseInteraction mismatchedRequests.putIfAbsent(interaction.request, mutableListOf()) mismatchedRequests[interaction.request]?.add(PactVerificationResult.PartialMismatch( matchResult.problems[interaction]!!.mismatches)) } else -> { mismatchedRequests.putIfAbsent(request, mutableListOf()) mismatchedRequests[request]?.add(PactVerificationResult.UnexpectedRequest(request)) } } return invalidResponse(request) } private fun invalidResponse(request: Request): Response { val body = "{ \"error\": \"Unexpected request : ${StringEscapeUtils.escapeJson(request.toString())}\" }" return Response(500, mutableMapOf("Access-Control-Allow-Origin" to listOf("*"), "Content-Type" to listOf("application/json"), "X-Pact-Unexpected-Request" to listOf("1")), OptionalBody.body(body.toByteArray(), au.com.dius.pact.core.model.ContentType.JSON)) } companion object : KLogging() } abstract class BaseJdkMockServer( pact: RequestResponsePact, config: MockProviderConfig, private val server: HttpServer, private var stopped: Boolean = false ) : HttpHandler, BaseMockServer(pact, config) { override fun handle(exchange: HttpExchange) { if (exchange.requestMethod == "OPTIONS" && exchange.requestHeaders.containsKey("X-PACT-BOOTCHECK")) { exchange.responseHeaders.add("X-PACT-BOOTCHECK", "true") exchange.sendResponseHeaders(200, 0) exchange.close() } else { try { val request = toPactRequest(exchange) logger.debug { "Received request: $request" } val response = generatePactResponse(request) logger.debug { "Generating response: $response" } pactResponseToHttpExchange(response, exchange) } catch (e: Exception) { logger.error(e) { "Failed to generate response" } pactResponseToHttpExchange(Response(500, mutableMapOf("Content-Type" to listOf("application/json")), OptionalBody.body("{\"error\": ${e.message}}".toByteArray(), au.com.dius.pact.core.model.ContentType.JSON)), exchange) } } } private fun pactResponseToHttpExchange(response: Response, exchange: HttpExchange) { val headers = response.headers exchange.responseHeaders.putAll(headers) val body = response.body if (body.isPresent()) { val bytes = body.unwrap() exchange.sendResponseHeaders(response.status, bytes.size.toLong()) exchange.responseBody.write(bytes) } else { exchange.sendResponseHeaders(response.status, 0) } exchange.close() } private fun toPactRequest(exchange: HttpExchange): Request { val headers = exchange.requestHeaders val contentType = contentType(headers) val bodyContents = when (bodyIsCompressed(headers.getFirst("Content-Encoding"))) { "gzip" -> GZIPInputStream(exchange.requestBody).readBytes() "deflate" -> DeflaterInputStream(exchange.requestBody).readBytes() else -> exchange.requestBody.readBytes() } val body = if (bodyContents.isEmpty()) { OptionalBody.empty() } else { OptionalBody.body(bodyContents, contentType) } return Request(exchange.requestMethod, exchange.requestURI.path, queryStringToMap(exchange.requestURI.rawQuery).toMutableMap(), headers.toMutableMap(), body) } private fun contentType(headers: Headers): au.com.dius.pact.core.model.ContentType { val contentType = headers.entries.find { it.key.toUpperCase() == "CONTENT-TYPE" } return if (contentType != null && contentType.value.isNotEmpty()) { au.com.dius.pact.core.model.ContentType(contentType.value.first()) } else { au.com.dius.pact.core.model.ContentType.JSON } } private fun initServer() { server.createContext("/", this) } override fun start() { logger.debug { "Starting mock server" } server.start() logger.debug { "Mock server started: ${server.address}" } } override fun stop() { if (!stopped) { stopped = true server.stop(0) logger.debug { "Mock server shutdown" } } } init { initServer() } override fun getUrl(): String { return if (config.port == 0) { "${config.scheme}://${server.address.hostName}:${server.address.port}" } else { config.url() } } override fun getPort(): Int = server.address.port companion object : KLogging() } open class MockHttpServer(pact: RequestResponsePact, config: MockProviderConfig) : BaseJdkMockServer(pact, config, HttpServer.create(config.address(), 0)) open class MockHttpsServer(pact: RequestResponsePact, config: MockProviderConfig) : BaseJdkMockServer(pact, config, HttpsServer.create(config.address(), 0)) fun calculateCharset(headers: Map<String, List<String?>>): Charset { val contentType = headers.entries.find { it.key.toUpperCase() == "CONTENT-TYPE" } val default = Charset.forName("UTF-8") if (contentType != null && contentType.value.isNotEmpty() && !contentType.value.first().isNullOrEmpty()) { try { return ContentType.parse(contentType.value.first())?.charset ?: default } catch (e: Exception) { BaseJdkMockServer.logger.debug(e) { "Failed to parse the charset from the content type header" } } } return default }
apache-2.0
2a1a17f5976670c9acdefb1f15b85336
37.00627
129
0.732267
4.38481
false
true
false
false
mdaniel/intellij-community
python/python-psi-impl/src/com/jetbrains/python/codeInsight/ConditionUtil.kt
12
10290
// 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. @file:JvmName("ConditionUtil") package com.jetbrains.python.codeInsight import com.intellij.openapi.project.Project import com.intellij.openapi.util.text.StringUtil import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import com.intellij.psi.PsiWhiteSpace import com.intellij.psi.util.PsiTreeUtil import com.intellij.psi.util.descendantsOfType import com.intellij.psi.util.parents import com.intellij.util.IncorrectOperationException import com.jetbrains.python.PyTokenTypes import com.jetbrains.python.psi.* import com.jetbrains.python.psi.impl.PyPsiUtils /** * Conditional expressions utility * * @author Vasya Aksyonov, Alexey.Ivanov */ private val comparisonStrings = hashMapOf( PyTokenTypes.LT to "<", PyTokenTypes.GT to ">", PyTokenTypes.EQEQ to "==", PyTokenTypes.LE to "<=", PyTokenTypes.GE to ">=", PyTokenTypes.NE to "!=", PyTokenTypes.NE_OLD to "<>" ) private val invertedComparisons = hashMapOf( PyTokenTypes.LT to PyTokenTypes.GE, PyTokenTypes.GT to PyTokenTypes.LE, PyTokenTypes.EQEQ to PyTokenTypes.NE, PyTokenTypes.LE to PyTokenTypes.GT, PyTokenTypes.GE to PyTokenTypes.LT, PyTokenTypes.NE to PyTokenTypes.EQEQ, PyTokenTypes.NE_OLD to PyTokenTypes.EQEQ ) private val validConditionalOperators = hashSetOf( PyTokenTypes.IS_KEYWORD, PyTokenTypes.IN_KEYWORD, PyTokenTypes.NOT_KEYWORD, PyTokenTypes.OR_KEYWORD, PyTokenTypes.AND_KEYWORD, *comparisonStrings.keys.toTypedArray() ) fun findComparisonNegationOperators(expression: PyBinaryExpression?): Pair<String, String>? { val comparisonExpression = findComparisonExpression(expression) ?: return null return comparisonStrings.getValue(comparisonExpression.operator) to comparisonStrings.getValue(invertedComparisons.getValue(comparisonExpression.operator)) } fun findComparisonExpression(expression: PyBinaryExpression?): PyBinaryExpression? { var comparisonExpression = expression while (comparisonExpression != null) { if (comparisonStrings.containsKey(comparisonExpression.operator)) { return comparisonExpression } comparisonExpression = PsiTreeUtil.getParentOfType(comparisonExpression, PyBinaryExpression::class.java) } return null } fun negateComparisonExpression(project: Project, file: PsiFile, expression: PyBinaryExpression?): PsiElement? { val comparisonExpression = findComparisonExpression(expression) ?: return null val level = LanguageLevel.forElement(file) val elementGenerator = PyElementGenerator.getInstance(project) val parent = findNonParenthesizedExpressionParent(comparisonExpression) val invertedOperator = invertedComparisons.getValue(comparisonExpression.operator) val invertedExpression = elementGenerator.createBinaryExpression( comparisonStrings.getValue(invertedOperator), comparisonExpression.leftExpression, comparisonExpression.rightExpression) if (parent is PyPrefixExpression && parent.operator === PyTokenTypes.NOT_KEYWORD) { return parent.replace(invertedExpression) } else { return comparisonExpression.replace(elementGenerator.createExpressionFromText(level, "not " + invertedExpression.text)) } } fun isValidConditionExpression(expression: PyExpression): Boolean { if (expression is PyParenthesizedExpression) { return expression.containedExpression != null && isValidConditionExpression(expression.containedExpression!!) } if (expression is PyPrefixExpression && expression.operator == PyTokenTypes.NOT_KEYWORD) { return expression.operand != null } if (expression is PyBinaryExpression) { if (expression.leftExpression == null || expression.rightExpression == null) { return false } if (expression.operator == PyTokenTypes.OR_KEYWORD || expression.operator == PyTokenTypes.AND_KEYWORD) { return expression.leftExpression != null && expression.rightExpression != null && isValidConditionExpression(expression.leftExpression) && isValidConditionExpression(expression.rightExpression!!) } return expression.operator in validConditionalOperators } return true } fun getInvertedConditionExpression(project: Project, file: PsiFile, expression: PyExpression): PyExpression { val level = LanguageLevel.forElement(file) val elementGenerator = PyElementGenerator.getInstance(project) return getInvertedConditionExpression(project, file, level, elementGenerator, expression, true) } private fun getInvertedConditionExpression( project: Project, file: PsiFile, level: LanguageLevel, generator: PyElementGenerator, expression: PyExpression, isTopLevelExpression: Boolean): PyExpression { if (expression is PyParenthesizedExpression) { return getInvertedConditionExpression( project, file, level, generator, expression.containedExpression!!, isTopLevelExpression) } if (expression is PyPrefixExpression && expression.operator == PyTokenTypes.NOT_KEYWORD) { val invertedExpression = expression.operand!! return if (isTopLevelExpression && !requiresParentheses(invertedExpression)) PyPsiUtils.flattenParens(invertedExpression)!!.copy() as PyExpression else invertedExpression.copy() as PyExpression } if (expression !is PyBinaryExpression) { val expressionBuilder = StringBuilder("not ") if (expression is PyAssignmentExpression || requiresParentheses(expression)) { expressionBuilder.append("(") expressionBuilder.append(expression.text) expressionBuilder.append(")") } else { expressionBuilder.append(expression.text) } return generator.createExpressionFromText(level, expressionBuilder.toString()) } if (expression.operator == PyTokenTypes.IS_KEYWORD) { val isNegative = expression.node.findChildByType(PyTokenTypes.NOT_KEYWORD) != null return generator.createBinaryExpression( if (isNegative) "is" else "is not", expression.leftExpression, expression.rightExpression) } if (expression.operator == PyTokenTypes.IN_KEYWORD) { return generator.createBinaryExpression( "not in", expression.leftExpression, expression.rightExpression) } if (expression.operator == PyTokenTypes.NOT_KEYWORD) { if (expression.node.findChildByType(PyTokenTypes.IN_KEYWORD) == null) { throw IncorrectOperationException("Unexpected NOT binary expression") } return generator.createBinaryExpression( "in", expression.leftExpression, expression.rightExpression) } if (expression.operator == PyTokenTypes.OR_KEYWORD) { return generator.createBinaryExpression( "and", getInvertedConditionExpression( project, file, level, generator, expression.leftExpression, false), getInvertedConditionExpression( project, file, level, generator, expression.rightExpression!!, false)) } if (expression.operator == PyTokenTypes.AND_KEYWORD) { val adjacentExpressions = mutableListOf<PyExpression>() var currentExpression = expression while (currentExpression is PyBinaryExpression && currentExpression.operator == PyTokenTypes.AND_KEYWORD) { adjacentExpressions.add(currentExpression.rightExpression!!) currentExpression = currentExpression.leftExpression } adjacentExpressions.add(currentExpression) val invertedExpressions = adjacentExpressions.asReversed().map { getInvertedConditionExpression( project, file, level, generator, it, false) } return createOrExpression(level, generator, invertedExpressions, isTopLevelExpression) } if (comparisonStrings.containsKey(expression.operator)) { val chainedExpressions = mutableListOf<PyExpression>() var currentExpression = expression while (currentExpression is PyBinaryExpression && comparisonStrings.containsKey(currentExpression.operator)) { val leftExpression = (currentExpression.leftExpression as? PyBinaryExpression)?.rightExpression ?: currentExpression.leftExpression val invertedOperator = invertedComparisons.getValue(currentExpression.operator) val invertedExpression = generator.createBinaryExpression( comparisonStrings.getValue(invertedOperator), leftExpression, currentExpression.rightExpression!!) chainedExpressions.add(invertedExpression) currentExpression = currentExpression.leftExpression } return createOrExpression(level, generator, chainedExpressions.asReversed(), isTopLevelExpression) } throw IncorrectOperationException("Is not a condition") } private fun findNonParenthesizedExpressionParent(element: PsiElement): PsiElement { var parent = element.parent while (parent is PyParenthesizedExpression) { parent = parent.getParent() } return parent } private fun requiresParentheses(element: PsiElement): Boolean { val allWhitespacesAreParenthesized = element.descendantsOfType<PsiWhiteSpace>().map { whitespace -> whitespace.parents(false).takeWhile { it != element }.firstOrNull { it is PyParenthesizedExpression || it is PyArgumentList } }.all { it != null } if (allWhitespacesAreParenthesized) { return false } var result = true var hasTrailingBackslash = false for (c in element.text) { when { StringUtil.isLineBreak(c) -> { result = result && hasTrailingBackslash hasTrailingBackslash = false } c == '\\' -> { hasTrailingBackslash = true } !StringUtil.isWhiteSpace(c) -> { hasTrailingBackslash = false } } } return !result } private fun createOrExpression( level: LanguageLevel, generator: PyElementGenerator, expressions: Iterable<PyExpression>, isTopLevelExpression: Boolean): PyExpression { val result = StringBuilder() val requiresParentheses = !isTopLevelExpression && expressions.count() > 1 if (requiresParentheses) { result.append("(") } expressions.forEachIndexed { i, expression -> if (i > 0) { result.append(" or ") } result.append(expression.text) } if (requiresParentheses) { result.append(")") } return generator.createExpressionFromText(level, result.toString()) }
apache-2.0
dc109af66a9d2d0db429f1e1014b0e92
35.105263
140
0.754519
4.987882
false
false
false
false
GunoH/intellij-community
platform/vcs-impl/src/com/intellij/openapi/vcs/changes/actions/ShelveSilentlyAction.kt
6
1536
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.vcs.changes.actions import com.intellij.openapi.actionSystem.ActionUpdateThread import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.fileEditor.FileDocumentManager import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.vcs.VcsDataKeys import com.intellij.openapi.vcs.changes.ChangeListManager import com.intellij.openapi.vcs.changes.shelf.ShelveChangesManager class ShelveSilentlyAction : ShelveSilentlyActionBase(rollbackChanges = true) class SaveToShelveAction : ShelveSilentlyActionBase(rollbackChanges = false) abstract class ShelveSilentlyActionBase(val rollbackChanges: Boolean) : DumbAwareAction() { override fun update(e: AnActionEvent) { val project = e.project val changes = e.getData(VcsDataKeys.CHANGES) e.presentation.isEnabled = project != null && !changes.isNullOrEmpty() && ChangeListManager.getInstance(project).areChangeListsEnabled() } override fun getActionUpdateThread(): ActionUpdateThread { return ActionUpdateThread.BGT } override fun actionPerformed(e: AnActionEvent) { val project = e.project!! val changes = e.getData(VcsDataKeys.CHANGES)!! FileDocumentManager.getInstance().saveAllDocuments() ShelveChangesManager.getInstance(project).shelveSilentlyUnderProgress(changes.toList(), rollbackChanges) } }
apache-2.0
db7cd04df640c4251af52e265f23fc7e
42.914286
140
0.791667
4.830189
false
false
false
false
GunoH/intellij-community
plugins/full-line/python/test/org/jetbrains/completion/full/line/python/features/RedCodeCompletionTest.kt
2
1624
package org.jetbrains.completion.full.line.python.features import org.jetbrains.completion.full.line.python.tests.FullLinePythonCompletionTestCase class RedCodeCompletionTest : FullLinePythonCompletionTestCase() { override fun getBasePath(): String = "testData/completion/features/red-code" fun `test full Python`() { myFixture.addFileToProject( "another.py", """ baseA = 1 baseC = "str" class Base: var1 = 1 def foo(): pass def var2(a, b): pass """.trimIndent() ) myFixture.addFileToProject( "main.py", """ import another from another import Base a = 1 b = "23" def fzz(): pass class A(Base): var3 = 1 def foo1(): pass new = A().<caret> """.trimIndent(), ) myFixture.configureByFile("main.py") testIfSuggestionsRefCorrect( *arrayOf( "another", "a", "b", "fzz", "A", "var3", "foo1", "test", "another.baseA", "another.baseC", "another.Base", "another.var1", "another.foo", "another.var2", "def", "pass", ).let { arr -> arr + arr.map { "$it()" } } ) testIfSuggestionsRefCorrect("none", "python", "main", "baseC", "baseA") } }
apache-2.0
4c921d9ba451bc0ea094bbb963fc8818
24.375
87
0.441502
4.666667
false
true
false
false
ftomassetti/kolasu
emf/src/test/kotlin/com/strumenta/kolasu/emf/rpgast/builtin_functions.kt
1
5493
package com.smeup.rpgparser.parsing.ast import com.strumenta.kolasu.model.Position // %LOOKUP // To be supported: // * %LOOKUPLT // * %LOOKUPLE // * %LOOKUPGT // * %LOOKUPGE data class LookupExpr( var searchedValued: Expression, val array: Expression, val specifiedPosition: Position? = null ) : Expression(specifiedPosition) // %SCAN data class ScanExpr( var value: Expression, val src: Expression, val start: Expression? = null, val specifiedPosition: Position? = null ) : Expression(specifiedPosition) // %XLATE data class TranslateExpr( var from: Expression, var to: Expression, var string: Expression, val startPos: Expression, val specifiedPosition: Position? = null ) : Expression(specifiedPosition) // %TRIM data class TrimExpr( var value: Expression, val charactersToTrim: Expression? = null, val specifiedPosition: Position? = null ) : Expression(specifiedPosition) { override fun render(): String { val toTrim = if (this.charactersToTrim != null) ": ${this.charactersToTrim.render()}" else "" return "%TRIM(${this.value.render()} $toTrim)" } } // %TRIMR data class TrimrExpr( var value: Expression, val charactersToTrim: Expression? = null, val specifiedPosition: Position? = null ) : Expression(specifiedPosition) { override fun render(): String { val toTrim = if (this.charactersToTrim != null) ": ${this.charactersToTrim.render()}" else "" return "%TRIMR(${this.value.render()} $toTrim)" } } // %TRIML data class TrimlExpr( var value: Expression, val charactersToTrim: Expression? = null, val specifiedPosition: Position? = null ) : Expression(specifiedPosition) { override fun render(): String { val toTrim = if (this.charactersToTrim != null) ": ${this.charactersToTrim.render()}" else "" return "%TRIMR(${this.value.render()} $toTrim)" } } // %SUBST data class SubstExpr( var string: Expression, val start: Expression, val length: Expression? = null, val specifiedPosition: Position? = null ) : AssignableExpression(specifiedPosition) { override fun render(): String { val len = if (length != null) ": ${length.render()}" else "" return "%SUBST(${this.string.render()} : ${start.render()} $len)" } override fun size(): Int { TODO("size") } } // %LEN data class LenExpr(var value: Expression, val specifiedPosition: Position? = null) : Expression(specifiedPosition) { override fun render(): String { return "%LEN(${this.value.render()})" } } // %REM data class RemExpr( val dividend: Expression, val divisor: Expression, val specifiedPosition: Position? = null ) : Expression(specifiedPosition) // %DEC data class DecExpr( var value: Expression, var intDigits: Expression, val decDigits: Expression, val specifiedPosition: Position? = null ) : Expression(specifiedPosition) { override fun render(): String { return "${this.value.render()}" } } // %INT data class IntExpr( var value: Expression, val specifiedPosition: Position? = null ) : Expression(specifiedPosition) { override fun render(): String { return "${this.value.render()}" } } // %SQRT data class SqrtExpr(var value: Expression, val specifiedPosition: Position? = null) : Expression(specifiedPosition) { override fun render(): String { return "${this.value.render()}" } } // %EDITC // TODO add other parameters data class EditcExpr( var value: Expression, val format: Expression, val specifiedPosition: Position? = null ) : Expression(specifiedPosition) // %EDITW // TODO add other parameters data class EditwExpr( var value: Expression, val format: Expression, val specifiedPosition: Position? = null ) : Expression(specifiedPosition) // %FOUND data class FoundExpr( var name: String? = null, val specifiedPosition: Position? = null ) : Expression(specifiedPosition) // %EOF data class EofExpr( var name: String? = null, val specifiedPosition: Position? = null ) : Expression(specifiedPosition) // %EQUAL data class EqualExpr( var name: String? = null, val specifiedPosition: Position? = null ) : Expression(specifiedPosition) // %ABS data class AbsExpr( var value: Expression, val specifiedPosition: Position? = null ) : Expression(specifiedPosition) // %CHAR data class CharExpr(var value: Expression, val format: String?, val specifiedPosition: Position? = null) : Expression(specifiedPosition) { override fun render(): String { return "%CHAR(${value.render()})" } } // %TIMESTAMP data class TimeStampExpr(val value: Expression?, val specifiedPosition: Position? = null) : Expression(specifiedPosition) // %DIFF data class DiffExpr( var value1: Expression, var value2: Expression, val durationCode: DurationCode, val specifiedPosition: Position? = null ) : Expression(specifiedPosition) // %REPLACE data class ReplaceExpr( val replacement: Expression, val src: Expression, val start: Expression? = null, val length: Expression? = null, val specifiedPosition: Position? = null ) : Expression(specifiedPosition) // TODO Move and handle different types of duration // TODO document what a duration code is sealed class DurationCode object DurationInMSecs : DurationCode() object DurationInDays : DurationCode()
apache-2.0
aba9a0755d4480a7154d1fd38a06dcd0
22.374468
106
0.675587
3.89851
false
false
false
false
himikof/intellij-rust
src/main/kotlin/org/rust/lang/core/parser/RustParserUtil.kt
1
7926
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.lang.core.parser import com.intellij.lang.* import com.intellij.lang.parser.GeneratedParserUtilBase import com.intellij.openapi.util.Key import com.intellij.psi.tree.IElementType import com.intellij.psi.tree.TokenSet import org.rust.lang.core.parser.RustParserDefinition.Companion.OUTER_BLOCK_DOC_COMMENT import org.rust.lang.core.parser.RustParserDefinition.Companion.OUTER_EOL_DOC_COMMENT import org.rust.lang.core.psi.RS_BLOCK_LIKE_EXPRESSIONS import org.rust.lang.core.psi.RsElementTypes import org.rust.lang.core.psi.RsElementTypes.* @Suppress("UNUSED_PARAMETER") object RustParserUtil : GeneratedParserUtilBase() { enum class PathParsingMode { COLONS, NO_COLONS, NO_TYPES } enum class BinaryMode { ON, OFF } private val STRUCT_ALLOWED: Key<Boolean> = Key("org.rust.STRUCT_ALLOWED") private val TYPE_QUAL_ALLOWED: Key<Boolean> = Key("org.rust.TYPE_QUAL_ALLOWED") private val PATH_PARSING_MODE: Key<PathParsingMode> = Key("org.rust.PATH_PARSING_MODE") private val STMT_EXPR_MODE: Key<Boolean> = Key("org.rust.STMT_EXPR_MODE") private val PsiBuilder.structAllowed: Boolean get() = getUserData(STRUCT_ALLOWED) ?: true private val PsiBuilder.pathParsingMode: PathParsingMode get() = requireNotNull(getUserData(PATH_PARSING_MODE)) { "Path context is not set. Be sure to call one of `withParsingMode...` functions" } @JvmField val DOC_COMMENT_BINDER: WhitespacesAndCommentsBinder = WhitespacesBinders.leadingCommentsBinder( TokenSet.create(OUTER_BLOCK_DOC_COMMENT, OUTER_EOL_DOC_COMMENT)) // // Helpers // @JvmStatic fun checkStructAllowed(b: PsiBuilder, level: Int): Boolean = b.structAllowed @JvmStatic fun checkTypeQualAllowed(b: PsiBuilder, level: Int): Boolean = b.getUserData(TYPE_QUAL_ALLOWED) ?: true @JvmStatic fun checkBraceAllowed(b: PsiBuilder, level: Int): Boolean { return b.structAllowed || b.tokenType != LBRACE } @JvmStatic fun structLiterals(b: PsiBuilder, level: Int, mode: BinaryMode, parser: Parser): Boolean = b.withContext(STRUCT_ALLOWED, mode == BinaryMode.ON) { parser.parse(this, level) } @JvmStatic fun typeQuals(b: PsiBuilder, level: Int, mode: BinaryMode, parser: Parser): Boolean = b.withContext(TYPE_QUAL_ALLOWED, mode == BinaryMode.ON) { parser.parse(this, level) } /** * Controls the difference between * * ``` * // bit and * let _ = {1} & x; * ``` * and * * ``` * // two statements: block expression {1} and unary reference expression &x * {1} & x; * ``` * * See `Restrictions::RESTRICTION_STMT_EXPR` in libsyntax */ @JvmStatic fun stmtMode(b: PsiBuilder, level: Int, mode: BinaryMode, parser: Parser): Boolean = b.withContext(STMT_EXPR_MODE, mode == BinaryMode.ON) { parser.parse(this, level) } @JvmStatic fun isCompleteBlockExpr(b: PsiBuilder, level: Int): Boolean { return isBlock(b, level) && b.getUserData(STMT_EXPR_MODE) == true } @JvmStatic fun isBlock(b: PsiBuilder, level: Int): Boolean { val m = b.latestDoneMarker ?: return false return m.tokenType in RS_BLOCK_LIKE_EXPRESSIONS || m.isBracedMacro(b) } @JvmStatic fun pathMode(b: PsiBuilder, level: Int, mode: PathParsingMode, parser: Parser): Boolean = b.withContext(PATH_PARSING_MODE, mode) { parser.parse(this, level) } @JvmStatic fun isPathMode(b: PsiBuilder, level: Int, mode: PathParsingMode): Boolean = mode == b.pathParsingMode @JvmStatic fun unpairedToken(b: PsiBuilder, level: Int): Boolean = when (b.tokenType) { LBRACE, RBRACE -> false LPAREN, RPAREN -> false LBRACK, RBRACK -> false else -> { b.advanceLexer() true } } @JvmStatic fun macroSemicolon(b: PsiBuilder, level: Int): Boolean { val m = b.latestDoneMarker ?: return false b.tokenText if (b.originalText[m.endOffset - 1] == '}') return true return consumeToken(b, SEMICOLON) } @JvmStatic fun macroIdentifier(b: PsiBuilder, level: Int): Boolean = when (b.tokenType) { TYPE_KW, CRATE, IDENTIFIER -> { b.advanceLexer() true } else -> false } @JvmStatic fun tupleOrParenType(b: PsiBuilder, level: Int, typeReference: Parser, tupeTypeUpper: Parser): Boolean { val tupleOrParens: PsiBuilder.Marker = enter_section_(b) if (!consumeTokenSmart(b, LPAREN)) { exit_section_(b, tupleOrParens, null, false) return false } val firstType = enter_section_(b) if (!typeReference.parse(b, level)) { exit_section_(b, firstType, null, false) exit_section_(b, tupleOrParens, null, false) return false } if (consumeTokenFast(b, RPAREN)) { exit_section_(b, firstType, null, true) exit_section_(b, tupleOrParens, null, true) return true } exit_section_(b, firstType, TYPE_REFERENCE, true) val result = tupeTypeUpper.parse(b, level) exit_section_(b, tupleOrParens, TUPLE_TYPE, result) return result } @JvmStatic fun gtgteqImpl(b: PsiBuilder, level: Int): Boolean = collapse(b, GTGTEQ, GT, GT, EQ) @JvmStatic fun gtgtImpl(b: PsiBuilder, level: Int): Boolean = collapse(b, GTGT, GT, GT) @JvmStatic fun gteqImpl(b: PsiBuilder, level: Int): Boolean = collapse(b, GTEQ, GT, EQ) @JvmStatic fun ltlteqImpl(b: PsiBuilder, level: Int): Boolean = collapse(b, LTLTEQ, LT, LT, EQ) @JvmStatic fun ltltImpl(b: PsiBuilder, level: Int): Boolean = collapse(b, LTLT, LT, LT) @JvmStatic fun lteqImpl(b: PsiBuilder, level: Int): Boolean = collapse(b, LTEQ, LT, EQ) @JvmStatic fun ororImpl(b: PsiBuilder, level: Int): Boolean = collapse(b, OROR, OR, OR) @JvmStatic fun andandImpl(b: PsiBuilder, level: Int): Boolean = collapse(b, ANDAND, AND, AND) @JvmStatic fun defaultKeyword(b: PsiBuilder, level: Int): Boolean = contextualKeyword(b, "default", DEFAULT) @JvmStatic fun unionKeyword(b: PsiBuilder, level: Int): Boolean = contextualKeyword(b, "union", UNION) private @JvmStatic fun collapse(b: PsiBuilder, tokenType: IElementType, vararg parts: IElementType): Boolean { // We do not want whitespace between parts, so firstly we do raw lookup for each part, // and when we make sure that we have desired token, we consume and collapse it. parts.forEachIndexed { i, tt -> if (b.rawLookup(i) != tt) return false } val marker = b.mark() PsiBuilderUtil.advance(b, parts.size) marker.collapse(tokenType) return true } private fun <T> PsiBuilder.withContext(key: Key<T>, value: T, block: PsiBuilder.() -> Boolean): Boolean { val old = getUserData(key) putUserData(key, value) val result = block() putUserData(key, old) return result } private fun LighterASTNode.isBracedMacro(b: PsiBuilder): Boolean = tokenType == RsElementTypes.MACRO_EXPR && '{' == b.originalText.subSequence(startOffset, endOffset).find { it == '{' || it == '[' || it == '(' } private fun contextualKeyword(b: PsiBuilder, keyword: String, elementType: IElementType): Boolean { // Tricky: the token can be already remapped by some previous rule that was backtracked if ((b.tokenType == IDENTIFIER && b.tokenText == keyword && !(b.lookAhead(1)?.equals(EXCL) ?: false)) || b.tokenType == elementType) { b.remapCurrentToken(elementType) b.advanceLexer() return true } return false } }
mit
48dfddaaea60c4285cefd5b3cc3b45ad
40.936508
142
0.647742
4.039755
false
false
false
false
jk1/intellij-community
java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/JavaSoftKeywordHighlighting.kt
3
2475
// 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.codeHighlighting.TextEditorHighlightingPass import com.intellij.codeHighlighting.TextEditorHighlightingPassFactory import com.intellij.codeHighlighting.TextEditorHighlightingPassRegistrar import com.intellij.lang.java.lexer.JavaLexer import com.intellij.openapi.components.AbstractProjectComponent import com.intellij.openapi.editor.Document import com.intellij.openapi.editor.Editor import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.project.Project import com.intellij.pom.java.LanguageLevel import com.intellij.psi.* class JavaSoftKeywordHighlightingPassFactory(project: Project, registrar: TextEditorHighlightingPassRegistrar) : AbstractProjectComponent(project), TextEditorHighlightingPassFactory { init { registrar.registerTextEditorHighlightingPass(this, null, null, false, -1) } override fun createHighlightingPass(file: PsiFile, editor: Editor): TextEditorHighlightingPass? { val visit = file is PsiJavaFile && (file.name == PsiJavaModule.MODULE_INFO_FILE && file.languageLevel.isAtLeast(LanguageLevel.JDK_1_9) || file.languageLevel.isAtLeast(LanguageLevel.JDK_10)) return if (visit) JavaSoftKeywordHighlightingPass(file as PsiJavaFile, editor.document) else null } } private class JavaSoftKeywordHighlightingPass(private val file: PsiJavaFile, document: Document) : TextEditorHighlightingPass(file.project, document) { private val results = mutableListOf<HighlightInfo>() override fun doCollectInformation(progress: ProgressIndicator) { file.accept(JavaSoftKeywordHighlightingVisitor(results, file.languageLevel)) } override fun doApplyInformationToEditor() { UpdateHighlightersUtil.setHighlightersToEditor(myProject, myDocument!!, 0, file.textLength, results, colorsScheme, id) } } private class JavaSoftKeywordHighlightingVisitor(private val results: MutableList<HighlightInfo>, private val level: LanguageLevel) : JavaRecursiveElementVisitor() { override fun visitKeyword(keyword: PsiKeyword) { if (JavaLexer.isSoftKeyword(keyword.node.chars, level)) { val info = HighlightInfo.newHighlightInfo(JavaHighlightInfoTypes.JAVA_KEYWORD).range(keyword).create() if (info != null) { results += info } } } }
apache-2.0
bb1518daff092306438b07138128e5a2
43.214286
140
0.794343
4.787234
false
false
false
false
ForgetAll/GankKotlin
app/src/main/java/com/xiasuhuei321/gankkotlin/modules/girls/adapter/GirlImageAdapter.kt
1
3586
package com.xiasuhuei321.gankkotlin.modules.girls.adapter import android.graphics.Bitmap import android.support.v4.app.Fragment import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.RelativeLayout import android.widget.TextView import com.bumptech.glide.Glide import com.bumptech.glide.request.animation.GlideAnimation import com.bumptech.glide.request.target.SimpleTarget import com.xiasuhuei321.gankkotlin.Global import com.xiasuhuei321.gankkotlin.R import com.xiasuhuei321.gankkotlin.data.Data import com.xiasuhuei321.gankkotlin.extension.getScreenWidth import com.xiasuhuei321.gankkotlin.util.XLog import java.util.ArrayList import java.util.HashMap class GirlImageAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() { private var data: List<Data> = ArrayList() private var notifyCount = 10 private var currentIndex = 0 var onItemClick: (Int) -> Unit = {} var fragment: Fragment? = null val sizeMap = HashMap<Int, Size>() fun setData(data: List<Data>?, startIndex: Int = currentIndex) { data?.let { this.data = it if (currentIndex != startIndex) currentIndex = startIndex XLog.i("data.size = ${data.size}") notifyItemRangeChanged(currentIndex, notifyCount) currentIndex += notifyCount } } override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): RecyclerView.ViewHolder { val view = LayoutInflater.from(parent?.context).inflate(R.layout.item_welfare, parent, false) return ImageHolder(view) } override fun getItemCount(): Int { return data.size } override fun onBindViewHolder(holder: RecyclerView.ViewHolder?, position: Int) { if (position >= data.size) return val h = holder as ImageHolder val data = data[position] h.timeTv.text = data.desc h.girlIv.setImageBitmap(null) val simpleTarget = object : SimpleTarget<Bitmap>() { override fun onResourceReady(resource: Bitmap?, glideAnimation: GlideAnimation<in Bitmap>?) { if (sizeMap[position] == null) { val width = Global.context.getScreenWidth() / 2 resource?.let { val ratio = it.height.toFloat() / it.width.toFloat() val height = width * ratio sizeMap.put(position, Size(width, height.toInt())) } } resizeView(position, h, resource) } } Glide.with(fragment).load(data.url).asBitmap().into(simpleTarget) h.rootRl.setOnClickListener { onItemClick.invoke(position) } } private fun resizeView(position: Int, holder: ImageHolder, bitmap: Bitmap?) { val params = holder.rootRl.layoutParams val size = sizeMap[position] size?.let { params.width = it.width params.height = it.height } holder.rootRl.layoutParams = params holder.girlIv.setImageBitmap(bitmap) } } data class Size(val width: Int, val height: Int) class ImageHolder : RecyclerView.ViewHolder { val girlIv: ImageView val timeTv: TextView val rootRl: RelativeLayout constructor(itemView: View) : super(itemView) { girlIv = itemView.findViewById(R.id.girlIv) timeTv = itemView.findViewById(R.id.timeTv) rootRl = itemView.findViewById(R.id.rootRl) } }
apache-2.0
1332020987d05841496020f3d47a5e49
33.490385
105
0.664529
4.315283
false
false
false
false
airbnb/lottie-android
sample-compose/src/main/java/com/airbnb/lottie/sample/compose/examples/BasicUsageExamplesPage.kt
1
5337
package com.airbnb.lottie.sample.compose.examples import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.material.Text 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.Modifier import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.airbnb.lottie.compose.LottieAnimation import com.airbnb.lottie.compose.LottieClipSpec import com.airbnb.lottie.compose.LottieCompositionSpec import com.airbnb.lottie.compose.LottieConstants import com.airbnb.lottie.compose.animateLottieCompositionAsState import com.airbnb.lottie.compose.rememberLottieComposition import com.airbnb.lottie.sample.compose.R @Composable fun BasicUsageExamplesPage() { UsageExamplePageScaffold { Column( modifier = Modifier .fillMaxWidth() .verticalScroll(rememberScrollState()) ) { Box(modifier = Modifier.height(16.dp)) ExampleCard("Example 1", "Repeat once") { Example1() } ExampleCard("Example 2", "Repeat forever") { Example2() } ExampleCard("Example 3", "Repeat forever from 50% to 75%") { Example3() } ExampleCard("Example 4", "Using LottieAnimationResult") { Example4() } ExampleCard("Example 5", "Using LottieComposition") { Example5() } ExampleCard("Example 6", "Splitting out the animation driver") { Example6() } ExampleCard("Example 7", "Toggle on click - click me") { Example7() } } } } /** * Nice and easy... This will play one time as soon as the composition loads * then it will stop. */ @Composable private fun Example1() { val composition by rememberLottieComposition(LottieCompositionSpec.RawRes(R.raw.heart)) LottieAnimation(composition) } /** * This will repeat forever. */ @Composable private fun Example2() { val composition by rememberLottieComposition(LottieCompositionSpec.RawRes(R.raw.heart)) LottieAnimation( composition, iterations = LottieConstants.IterateForever, ) } /** * This will repeat between 50% and 75% forever. */ @Composable private fun Example3() { val composition by rememberLottieComposition(LottieCompositionSpec.RawRes(R.raw.heart)) LottieAnimation( composition, iterations = LottieConstants.IterateForever, clipSpec = LottieClipSpec.Progress(0.5f, 0.75f), ) } /** * Here, you can check the result for loading/failure states. */ @Composable private fun Example4() { val compositionResult = rememberLottieComposition(LottieCompositionSpec.RawRes(R.raw.heart)) when { compositionResult.isLoading -> { Text("Animation is loading...") } compositionResult.isFailure -> { Text("Animation failed to load") } compositionResult.isSuccess -> { LottieAnimation( compositionResult.value, iterations = LottieConstants.IterateForever, ) } } } /** * If you just want access to the composition itself, you can use the delegate * version of lottieComposition like this. */ @Composable private fun Example5() { val composition by rememberLottieComposition(LottieCompositionSpec.RawRes(R.raw.heart)) LottieAnimation( composition, progress = { 0.65f }, ) } /** * Here, you have access to the composition and animation individually. */ @Composable private fun Example6() { val composition by rememberLottieComposition(LottieCompositionSpec.RawRes(R.raw.heart)) val progress by animateLottieCompositionAsState( composition, iterations = LottieConstants.IterateForever, ) LottieAnimation( composition, { progress }, ) } /** * Here, you can toggle playback by clicking the animation. */ @Composable private fun Example7() { val composition by rememberLottieComposition(LottieCompositionSpec.RawRes(R.raw.heart)) var isPlaying by remember { mutableStateOf(false) } LottieAnimation( composition, iterations = LottieConstants.IterateForever, // When this is true, it it will start from 0 every time it is played again. // When this is false, it will resume from the progress it was pause at. restartOnPlay = false, isPlaying = isPlaying, modifier = Modifier .clickable { isPlaying = !isPlaying } ) } @Preview @Composable fun ExampleCardPreview() { val composition by rememberLottieComposition(LottieCompositionSpec.RawRes(R.raw.heart)) ExampleCard("Example 1", "Heart animation") { LottieAnimation(composition) } }
apache-2.0
4d83b44340ad738429a0e0d597553145
29.855491
96
0.680907
4.790844
false
false
false
false
pureal-code/pureal-os
traits/src/net/pureal/traits/interaction/KeyDefinition.kt
1
1000
package net.pureal.traits.interaction import net.pureal.traits.* trait KeyDefinition { val command: Command val alternativeCommands: Iterable<Command> get() = listOf() val name: String get() = command.name } fun keyDefinition(command: Command, alternativeCommands: Iterable<Command> = listOf(), name: String = command.name) = object : KeyDefinition { override val command = command override val alternativeCommands = alternativeCommands override val name = name } object KeyDefinitions { fun left(command: Command, alternativeCommands: Iterable<Command> = listOf()) = keyDefinition(command, alternativeCommands, "left ${command.name}") fun right(command: Command, alternativeCommands: Iterable<Command> = listOf()) = keyDefinition(command, alternativeCommands, "right ${command.name}") fun numPad(command: Command, alternativeCommands: Iterable<Command> = listOf()) = keyDefinition(command, alternativeCommands, "num pad ${command.name}") }
bsd-3-clause
4f971f789a18a1dedb5b4c4ab03e0a80
45.714286
156
0.736
4.424779
false
false
false
false
code-disaster/lwjgl3
modules/lwjgl/llvm/src/templates/kotlin/llvm/templates/LLVMTargetMachine.kt
4
6867
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license */ package llvm.templates import llvm.* import org.lwjgl.generator.* val LLVMTargetMachine = "LLVMTargetMachine".nativeClass( Module.LLVM, prefixConstant = "LLVM", prefixMethod = "LLVM", binding = LLVM_BINDING_DELEGATE ) { documentation = "" EnumConstant( "{@code LLVMCodeGenOptLevel}", "CodeGenLevelNone".enum("", "0"), "CodeGenLevelLess".enum, "CodeGenLevelDefault".enum, "CodeGenLevelAggressive".enum ) EnumConstant( "{@code LLVMRelocMode}", "RelocDefault".enum("", "0"), "RelocStatic".enum, "RelocPIC".enum, "RelocDynamicNoPic".enum, "RelocROPI".enum, "RelocRWPI".enum, "RelocROPI_RWPI".enum ) EnumConstant( "{@code LLVMCodeModel}", "CodeModelDefault".enum("", "0"), "CodeModelJITDefault".enum, "CodeModelTiny".enum, "CodeModelSmall".enum, "CodeModelKernel".enum, "CodeModelMedium".enum, "CodeModelLarge".enum ) EnumConstant( "{@code LLVMCodeGenFileType}", "AssemblyFile".enum("", "0"), "ObjectFile".enum ) LLVMTargetRef( "GetFirstTarget", "Returns the first {@code llvm::Target} in the registered targets list.", void() ) LLVMTargetRef( "GetNextTarget", "Returns the next {@code llvm::Target} given a previous one (or null if there's none)", LLVMTargetRef("T", "") ) LLVMTargetRef( "GetTargetFromName", "Finds the target corresponding to the given name and stores it in {@code T}. Returns 0 on success.", charUTF8.const.p("Name", "") ) LLVMBool( "GetTargetFromTriple", """ Finds the target corresponding to the given triple and stores it in {@code T}. Returns 0 on success. Optionally returns any error in {@code ErrorMessage}. Use #DisposeMessage() to dispose the message. """, charUTF8.const.p("Triple", ""), Check(1)..LLVMTargetRef.p("T", ""), Check(1)..charUTF8.p.p("ErrorMessage", "") ) charUTF8.const.p( "GetTargetName", "Returns the name of a target. See {@code llvm::Target::getName}", LLVMTargetRef("T", "") ) charUTF8.const.p( "GetTargetDescription", "Returns the description of a target. See {@code llvm::Target::getDescription}", LLVMTargetRef("T", "") ) LLVMBool( "TargetHasJIT", "Returns if the target has a JIT", LLVMTargetRef("T", "") ) LLVMBool( "TargetHasTargetMachine", "Returns if the target has a {@code TargetMachine} associated", LLVMTargetRef("T", "") ) LLVMBool( "TargetHasAsmBackend", "Returns if the target as an ASM backend (required for emitting output)", LLVMTargetRef("T", "") ) LLVMTargetMachineRef( "CreateTargetMachine", "Creates a new {@code llvm::TargetMachine}. See {@code llvm::Target::createTargetMachine}", LLVMTargetRef("T", ""), charUTF8.const.p("Triple", ""), charUTF8.const.p("CPU", ""), charUTF8.const.p("Features", ""), LLVMCodeGenOptLevel("Level", ""), LLVMRelocMode("Reloc", ""), LLVMCodeModel("CodeModel", "") ) void( "DisposeTargetMachine", "Dispose the {@code LLVMTargetMachineRef} instance generated by #CreateTargetMachine().", LLVMTargetMachineRef("T", "") ) LLVMTargetRef( "GetTargetMachineTarget", "Returns the {@code Target} used in a {@code TargetMachine}", LLVMTargetMachineRef("T", "") ) charUTF8.p( "GetTargetMachineTriple", """ Returns the triple used creating this target machine. See {@code llvm::TargetMachine::getTriple}. The result needs to be disposed with #DisposeMessage(). """, LLVMTargetMachineRef("T", "") ) charUTF8.p( "GetTargetMachineCPU", "Returns the cpu used creating this target machine. See {@code llvm::TargetMachine::getCPU}. The result needs to be disposed with #DisposeMessage().", LLVMTargetMachineRef("T", "") ) charUTF8.p( "GetTargetMachineFeatureString", """ Returns the feature string used creating this target machine. See {@code llvm::TargetMachine::getFeatureString}. The result needs to be disposed with #DisposeMessage(). """, LLVMTargetMachineRef("T", "") ) LLVMTargetDataRef( "CreateTargetDataLayout", "Create a {@code DataLayout} based on the target machine.", LLVMTargetMachineRef("T", "") ) void( "SetTargetMachineAsmVerbosity", "Set the target machine's ASM verbosity.", LLVMTargetMachineRef("T", ""), LLVMBool("VerboseAsm", "") ) LLVMBool( "TargetMachineEmitToFile", """ Emits an asm or object file for the given module to the filename. This wraps several c++ only classes (among them a file stream). Returns any error in {@code ErrorMessage}. Use #DisposeMessage() to dispose the message. """, LLVMTargetMachineRef("T", ""), LLVMModuleRef("M", ""), charUTF8.p("Filename", ""), LLVMCodeGenFileType("codegen", ""), Check(1)..charUTF8.p.p("ErrorMessage", "") ) LLVMBool( "TargetMachineEmitToMemoryBuffer", "Compile the LLVM IR stored in {@code M} and store the result in {@code OutMemBuf}.", LLVMTargetMachineRef("T", ""), LLVMModuleRef("M", ""), LLVMCodeGenFileType("codegen", ""), Check(1)..charUTF8.p.p("ErrorMessage", ""), Check(1)..LLVMMemoryBufferRef.p("OutMemBuf", "") ) charUTF8.p( "GetDefaultTargetTriple", "Get a triple for the host machine as a string. The result needs to be disposed with #DisposeMessage().", void() ) IgnoreMissing..charUTF8.p( "NormalizeTargetTriple", "Normalize a target triple. The result needs to be disposed with #DisposeMessage().", charUTF8.const.p("triple", "") ) IgnoreMissing..charUTF8.p( "GetHostCPUName", "Get the host CPU as a string. The result needs to be disposed with #DisposeMessage().", void() ) IgnoreMissing..charUTF8.p( "GetHostCPUFeatures", "Get the host CPU's features as a string. The result needs to be disposed with #DisposeMessage().", void() ) void( "AddAnalysisPasses", "Adds the target-specific analysis passes to the pass manager.", LLVMTargetMachineRef("T", ""), LLVMPassManagerRef("PM", "") ) }
bsd-3-clause
a73994a48095e63bce126b1cca9f42d7
25.933333
158
0.592544
4.470703
false
false
false
false
ClearVolume/scenery
src/main/kotlin/graphics/scenery/backends/vulkan/VulkanSwapchain.kt
1
26557
package graphics.scenery.backends.vulkan import graphics.scenery.Hub import graphics.scenery.backends.RenderConfigReader import graphics.scenery.backends.SceneryWindow import graphics.scenery.utils.LazyLogger import graphics.scenery.utils.SceneryPanel import org.lwjgl.glfw.GLFW.* import org.lwjgl.glfw.GLFWVulkan import org.lwjgl.glfw.GLFWWindowSizeCallback import org.lwjgl.system.MemoryStack.stackPush import org.lwjgl.system.MemoryUtil import org.lwjgl.system.MemoryUtil.memFree import org.lwjgl.vulkan.* import org.lwjgl.vulkan.KHRSurface.vkDestroySurfaceKHR import org.lwjgl.vulkan.KHRSwapchain.VK_ERROR_OUT_OF_DATE_KHR import org.lwjgl.vulkan.KHRSwapchain.vkAcquireNextImageKHR import org.lwjgl.vulkan.VK10.* import java.nio.IntBuffer import java.nio.LongBuffer import java.util.* /** * GLFW-based default Vulkan Swapchain and window, residing on [device], associated with [queue]. * Needs to be given [commandPools] to allocate command buffers from. [useSRGB] determines whether * the sRGB colorspace will be used, [vsync] determines whether vertical sync will be forced (swapping * rendered images in sync with the screen's frequency). [undecorated] determines whether the created * window will have the window system's default chrome or not. * * @author Ulrik Günther <[email protected]> */ open class VulkanSwapchain(open val device: VulkanDevice, open val queue: VkQueue, open val commandPools: VulkanRenderer.CommandPools, @Suppress("unused") open val renderConfig: RenderConfigReader.RenderConfig, open val useSRGB: Boolean = true, open val vsync: Boolean = false, open val undecorated: Boolean = false) : Swapchain { protected val logger by LazyLogger() /** Swapchain handle. */ override var handle: Long = 0L /** Array for rendered images. */ override var images: LongArray = LongArray(0) /** Array for image views. */ override var imageViews: LongArray = LongArray(0) /** Number of frames presented with this swapchain. */ protected var presentedFrames: Long = 0 /** Color format for the swapchain images. */ override var format: Int = 0 /** Swapchain image. */ var swapchainImage: IntBuffer = MemoryUtil.memAllocInt(1) /** Pointer to the current swapchain. */ var swapchainPointer: LongBuffer = MemoryUtil.memAllocLong(1) /** Present info, allocated only once and reused. */ var presentInfo: VkPresentInfoKHR = VkPresentInfoKHR.calloc() /** Vulkan queue used exclusively for presentation. */ lateinit var presentQueue: VkQueue /** Surface of the window to render into. */ open var surface: Long = 0 /** [SceneryWindow] instance we are using. */ open lateinit var window: SceneryWindow /** Callback to use upon window resizing. */ lateinit var windowSizeCallback: GLFWWindowSizeCallback /** Time in ns of the last resize event. */ var lastResize = -1L private val WINDOW_RESIZE_TIMEOUT = 200 * 10e6 private val retiredSwapchains: Queue<Pair<VulkanDevice, Long>> = ArrayDeque() protected var imageAvailableSemaphores = ArrayList<Long>() protected var imageRenderedSemaphores = ArrayList<Long>() protected var fences = ArrayList<Long>() protected var inFlight = ArrayList<Long?>() protected var imageUseFences = ArrayList<Long>() /** Current swapchain image in use */ var currentImage = 0 protected set /** Returns the currently-used semaphore to indicate image availability. */ override val imageAvailableSemaphore: Long get() { return imageAvailableSemaphores[currentImage] } /** Returns the currently-used fence. */ override val currentFence: Long get() { return fences[currentImage] } /** * Data class for summarising [colorFormat] and [colorSpace] information. */ data class ColorFormatAndSpace(var colorFormat: Int = 0, var colorSpace: Int = 0) /** * Creates a window for this swapchain, and initialiases [win] as [SceneryWindow.GLFWWindow]. * Needs to be handed a [VulkanRenderer.SwapchainRecreator]. * Returns the initialised [SceneryWindow]. */ override fun createWindow(win: SceneryWindow, swapchainRecreator: VulkanRenderer.SwapchainRecreator): SceneryWindow { glfwDefaultWindowHints() glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API) var windowPos = if(undecorated) { glfwWindowHint(GLFW_DECORATED, GLFW_FALSE) 0 to 0 } else { 100 to 100 } window = SceneryWindow.GLFWWindow(glfwCreateWindow(win.width, win.height, "scenery", MemoryUtil.NULL, MemoryUtil.NULL)).apply { width = win.width height = win.height glfwSetWindowPos(window, windowPos.first, windowPos.second) surface = VU.getLong("glfwCreateWindowSurface", { GLFWVulkan.glfwCreateWindowSurface(device.instance, window, null, this) }, {}) // Handle canvas resize windowSizeCallback = object : GLFWWindowSizeCallback() { override operator fun invoke(glfwWindow: Long, w: Int, h: Int) { if (lastResize > 0L && lastResize + WINDOW_RESIZE_TIMEOUT < System.nanoTime()) { lastResize = System.nanoTime() return } if (width <= 0 || height <= 0) return width = w height = h swapchainRecreator.mustRecreate = true lastResize = -1L } } glfwSetWindowSizeCallback(window, windowSizeCallback) glfwShowWindow(window) } return window } /** * Finds the best supported presentation mode, given the supported modes in [presentModes]. * The preferred mode can be selected via [preferredMode]. Returns the preferred mode, or * VK_PRESENT_MODE_FIFO, if the preferred one is not supported. */ private fun findBestPresentMode(presentModes: IntBuffer, preferredMode: Int): Int { val modes = IntArray(presentModes.capacity()) presentModes.get(modes) logger.debug("Available swapchain present modes: ${modes.joinToString(", ") { swapchainModeToName(it) }}") return if(modes.contains(preferredMode) || preferredMode == KHRSurface.VK_PRESENT_MODE_IMMEDIATE_KHR) { preferredMode } else { // VK_PRESENT_MODE_FIFO_KHR is always guaranteed to be available KHRSurface.VK_PRESENT_MODE_FIFO_KHR } } private fun swapchainModeToName(id: Int): String { return when(id) { 0 -> "VK_PRESENT_MODE_IMMEDIATE_KHR" 1 -> "VK_PRESENT_MODE_MAILBOX_KHR" 2 -> "VK_PRESENT_MODE_FIFO_KHR" 3 -> "VK_PRESENT_MODE_FIFO_RELAXED_KHR" else -> "(unknown swapchain mode)" } } /** * Creates a new swapchain and returns it, potentially recycling or deallocating [oldSwapchain]. */ override fun create(oldSwapchain: Swapchain?): Swapchain { presentedFrames = 0 return stackPush().use { stack -> val colorFormatAndSpace = getColorFormatAndSpace() val oldHandle = oldSwapchain?.handle // Get physical device surface properties and formats val surfCaps = VkSurfaceCapabilitiesKHR.callocStack(stack) VU.run("Getting surface capabilities", { KHRSurface.vkGetPhysicalDeviceSurfaceCapabilitiesKHR(device.physicalDevice, surface, surfCaps) }) val presentModeCount = VU.getInts("Getting present mode count", 1 ) { KHRSurface.vkGetPhysicalDeviceSurfacePresentModesKHR(device.physicalDevice, surface, this, null) } val presentModes = VU.getInts("Getting present modes", presentModeCount.get(0) ) { KHRSurface.vkGetPhysicalDeviceSurfacePresentModesKHR(device.physicalDevice, surface, presentModeCount, this) } // we prefer to use mailbox mode, if it is supported. mailbox uses triple-buffering // to avoid the latency issues fifo has. if the requested mode is not supported, // we will fall back to fifo, which is always guaranteed to be supported. // if vsync is not requested, we run in immediate mode, which may cause tearing, // but runs at maximum fps. val preferredSwapchainPresentMode = if(vsync) { KHRSurface.VK_PRESENT_MODE_FIFO_KHR } else { KHRSurface.VK_PRESENT_MODE_IMMEDIATE_KHR } val swapchainPresentMode = findBestPresentMode(presentModes, preferredSwapchainPresentMode) // Determine the number of images var desiredNumberOfSwapchainImages = 3//surfCaps.minImageCount() if (surfCaps.maxImageCount() in 1 until desiredNumberOfSwapchainImages) { desiredNumberOfSwapchainImages = surfCaps.maxImageCount() } logger.info("Selected present mode: ${swapchainModeToName(swapchainPresentMode)} with $desiredNumberOfSwapchainImages images") val currentWidth = surfCaps.currentExtent().width() val currentHeight = surfCaps.currentExtent().height() if (currentWidth > 0 && currentHeight > 0) { window.width = currentWidth window.height = currentHeight } else { // TODO: Better default values window.width = 1920 window.height = 1200 } val preTransform = if (surfCaps.supportedTransforms() and KHRSurface.VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR != 0) { KHRSurface.VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR } else { surfCaps.currentTransform() } val swapchainCI = VkSwapchainCreateInfoKHR.callocStack(stack) .sType(KHRSwapchain.VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR) .pNext(MemoryUtil.NULL) .surface(surface) .minImageCount(desiredNumberOfSwapchainImages) .imageFormat(colorFormatAndSpace.colorFormat) .imageColorSpace(colorFormatAndSpace.colorSpace) .imageUsage(VK10.VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT or VK10.VK_IMAGE_USAGE_TRANSFER_SRC_BIT or VK10.VK_IMAGE_USAGE_SAMPLED_BIT) .preTransform(preTransform) .imageArrayLayers(1) .imageSharingMode(VK10.VK_SHARING_MODE_EXCLUSIVE) .pQueueFamilyIndices(null) .presentMode(swapchainPresentMode) .clipped(true) .compositeAlpha(KHRSurface.VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR) // TODO: Add recycleable property for swapchains if ((oldSwapchain is VulkanSwapchain) && oldHandle != null) { swapchainCI.oldSwapchain(oldHandle) } swapchainCI.imageExtent().width(window.width).height(window.height) handle = VU.getLong("Creating swapchain", { KHRSwapchain.vkCreateSwapchainKHR(device.vulkanDevice, swapchainCI, null, this) }, {}) // If we just re-created an existing swapchain, we should destroy the old swapchain at this point. // Note: destroying the swapchain also cleans up all its associated presentable images once the platform is done with them. if (oldSwapchain is VulkanSwapchain && oldHandle != null && oldHandle != VK10.VK_NULL_HANDLE) { // TODO: Figure out why deleting a retired swapchain crashes on Nvidia // KHRSwapchain.vkDestroySwapchainKHR(device.vulkanDevice, oldHandle, null) retiredSwapchains.add(device to oldHandle) } val imageCount = VU.getInts("Getting swapchain images", 1, { KHRSwapchain.vkGetSwapchainImagesKHR(device.vulkanDevice, handle, this, null) }) logger.debug("Got ${imageCount.get(0)} swapchain images") val swapchainImages = VU.getLongs("Getting swapchain images", imageCount.get(0), { KHRSwapchain.vkGetSwapchainImagesKHR(device.vulkanDevice, handle, imageCount, this) }, {}) val images = LongArray(imageCount.get(0)) val imageViews = LongArray(imageCount.get(0)) val colorAttachmentView = VkImageViewCreateInfo.callocStack(stack) .sType(VK10.VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO) .pNext(MemoryUtil.NULL) .format(colorFormatAndSpace.colorFormat) .viewType(VK10.VK_IMAGE_VIEW_TYPE_2D) .flags(0) colorAttachmentView.components() .r(VK10.VK_COMPONENT_SWIZZLE_R) .g(VK10.VK_COMPONENT_SWIZZLE_G) .b(VK10.VK_COMPONENT_SWIZZLE_B) .a(VK10.VK_COMPONENT_SWIZZLE_A) colorAttachmentView.subresourceRange() .aspectMask(VK10.VK_IMAGE_ASPECT_COLOR_BIT) .baseMipLevel(0) .levelCount(1) .baseArrayLayer(0) .layerCount(1) val semaphoreCreateInfo = VkSemaphoreCreateInfo.calloc() .sType(VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO) val fenceCreateInfo = VkFenceCreateInfo.calloc() .sType(VK_STRUCTURE_TYPE_FENCE_CREATE_INFO) with(VU.newCommandBuffer(device, commandPools.Standard, autostart = true)) { for (i in 0 until imageCount.get(0)) { images[i] = swapchainImages.get(i) VU.setImageLayout(this, images[i], aspectMask = VK10.VK_IMAGE_ASPECT_COLOR_BIT, oldImageLayout = VK10.VK_IMAGE_LAYOUT_UNDEFINED, newImageLayout = KHRSwapchain.VK_IMAGE_LAYOUT_PRESENT_SRC_KHR) colorAttachmentView.image(images[i]) imageViews[i] = VU.getLong("create image view", { VK10.vkCreateImageView([email protected], colorAttachmentView, null, this) }, {}) imageAvailableSemaphores.add([email protected]()) imageRenderedSemaphores.add([email protected]()) fences.add(VU.getLong("Swapchain image fence", { vkCreateFence([email protected], fenceCreateInfo, null, this)}, {})) imageUseFences.add(VU.getLong("Swapchain image usage fence", { vkCreateFence([email protected], fenceCreateInfo, null, this)}, {})) inFlight.add(null) } endCommandBuffer([email protected], commandPools.Standard, queue, flush = true, dealloc = true) } this.images = images this.imageViews = imageViews this.format = colorFormatAndSpace.colorFormat semaphoreCreateInfo.free() memFree(swapchainImages) memFree(imageCount) memFree(presentModeCount) memFree(presentModes) this } } /** * Returns the [ColorFormatAndSpace] supported by the [device]. */ protected fun getColorFormatAndSpace(): ColorFormatAndSpace { return stackPush().use { stack -> val queueFamilyPropertyCount = stack.callocInt(1) VK10.vkGetPhysicalDeviceQueueFamilyProperties(device.physicalDevice, queueFamilyPropertyCount, null) val queueCount = queueFamilyPropertyCount.get(0) val queueProps = VkQueueFamilyProperties.callocStack(queueCount, stack) VK10.vkGetPhysicalDeviceQueueFamilyProperties(device.physicalDevice, queueFamilyPropertyCount, queueProps) // Iterate over each queue to learn whether it supports presenting: val supportsPresent = (0 until queueCount).map { VU.getInt("Physical device surface support", { KHRSurface.vkGetPhysicalDeviceSurfaceSupportKHR(device.physicalDevice, it, surface, this) }) } // Search for a graphics and a present queue in the array of queue families, try to find one that supports both var graphicsQueueNodeIndex = Integer.MAX_VALUE var presentQueueNodeIndex = Integer.MAX_VALUE for (i in 0 until queueCount) { if (queueProps.get(i).queueFlags() and VK10.VK_QUEUE_GRAPHICS_BIT != 0) { if (graphicsQueueNodeIndex == Integer.MAX_VALUE) { graphicsQueueNodeIndex = i } if (supportsPresent[i] == VK10.VK_TRUE) { graphicsQueueNodeIndex = i presentQueueNodeIndex = i break } } } if (presentQueueNodeIndex == Integer.MAX_VALUE) { // If there's no queue that supports both present and graphics try to find a separate present queue for (i in 0 until queueCount) { if (supportsPresent[i] == VK10.VK_TRUE) { presentQueueNodeIndex = i break } } } // Generate error if could not find both a graphics and a present queue if (graphicsQueueNodeIndex == Integer.MAX_VALUE) { throw RuntimeException("No graphics queue found") } if (presentQueueNodeIndex == Integer.MAX_VALUE) { throw RuntimeException("No presentation queue found") } if (graphicsQueueNodeIndex != presentQueueNodeIndex) { throw RuntimeException("Presentation queue != graphics queue") } presentQueue = VkQueue(VU.getPointer("Get present queue", { VK10.vkGetDeviceQueue(device.vulkanDevice, presentQueueNodeIndex, 0, this); VK10.VK_SUCCESS }, {}), device.vulkanDevice) // Get list of supported formats val formatCount = VU.getInts("Getting supported surface formats", 1, { KHRSurface.vkGetPhysicalDeviceSurfaceFormatsKHR(device.physicalDevice, surface, this, null) }) val surfFormats = VkSurfaceFormatKHR.callocStack(formatCount.get(0), stack) VU.run("Query device physical surface formats", { KHRSurface.vkGetPhysicalDeviceSurfaceFormatsKHR(device.physicalDevice, surface, formatCount, surfFormats) }) val colorFormat = if (useSRGB) { VK10.VK_FORMAT_B8G8R8A8_SRGB } else { VK10.VK_FORMAT_B8G8R8A8_UNORM } val colorSpace = if (useSRGB) { KHRSurface.VK_COLOR_SPACE_SRGB_NONLINEAR_KHR } else { surfFormats.get(0).colorSpace() } memFree(formatCount) ColorFormatAndSpace(colorFormat, colorSpace) } } /** * Presents the current swapchain image on screen. */ override fun present(waitForSemaphores: LongBuffer?) { // Present the current buffer to the swap chain // This will display the image swapchainPointer.put(0, handle) // Info struct to present the current swapchain image to the display presentInfo .sType(KHRSwapchain.VK_STRUCTURE_TYPE_PRESENT_INFO_KHR) .pNext(MemoryUtil.NULL) .swapchainCount(swapchainPointer.remaining()) .pSwapchains(swapchainPointer) .pImageIndices(swapchainImage) .pResults(null) waitForSemaphores?.let { presentInfo.pWaitSemaphores(it) } // logger.info("Presenting to image ${swapchainImage.get(0)}") // here we accept the VK_ERROR_OUT_OF_DATE_KHR error code, which // seems to spuriously occur on Linux upon resizing. VU.run("Presenting swapchain image", { KHRSwapchain.vkQueuePresentKHR(presentQueue, presentInfo) }, allowedResults = listOf(VK_ERROR_OUT_OF_DATE_KHR)) presentedFrames++ } /** * To be called after presenting, will deallocate retired swapchains. */ override fun postPresent(image: Int) { while(retiredSwapchains.isNotEmpty()) { retiredSwapchains.poll()?.let { KHRSwapchain.vkDestroySwapchainKHR(it.first.vulkanDevice, it.second, null) } } currentImage = (currentImage + 1) % images.size } /** * Acquires the next swapchain image. */ override fun next(timeout: Long): Pair<Long, Long>? { // logger.info("Acquiring next image with semaphore ${imageAvailableSemaphores[currentImage].toHexString()}, currentImage=$currentImage") val err = vkAcquireNextImageKHR(device.vulkanDevice, handle, timeout, imageAvailableSemaphores[currentImage], imageUseFences[currentImage], swapchainImage) // logger.info("Acquired image ${swapchainImage.get(0)}") if (err == KHRSwapchain.VK_ERROR_OUT_OF_DATE_KHR || err == KHRSwapchain.VK_SUBOPTIMAL_KHR) { return null } else if (err != VK10.VK_SUCCESS) { throw AssertionError("Failed to acquire next swapchain image: " + VU.translate(err)) } val imageIndex = swapchainImage.get(0) // wait for the present queue to become idle - by doing this here // we avoid stalling the GPU and gain a few FPS // val fence = inFlight[imageIndex] // if(fence != null) { // logger.info("Waiting on fence ${fence.toHexString()} for image $imageIndex") // vkWaitForFences(device.vulkanDevice, fence, true, -1L) // vkResetFences(device.vulkanDevice, fence) // } inFlight[imageIndex] = fences[currentImage] return imageAvailableSemaphores[currentImage] to imageUseFences[currentImage]//swapchainImage.get(0) } /** * Changes the current window to fullscreen. */ override fun toggleFullscreen(hub: Hub, swapchainRecreator: VulkanRenderer.SwapchainRecreator) { (window as SceneryWindow.GLFWWindow?)?.let { window -> if (window.isFullscreen) { glfwSetWindowMonitor(window.window, MemoryUtil.NULL, 0, 0, window.width, window.height, GLFW_DONT_CARE) glfwSetWindowPos(window.window, 100, 100) glfwSetInputMode(window.window, GLFW_CURSOR, GLFW_CURSOR_NORMAL) swapchainRecreator.mustRecreate = true window.isFullscreen = false } else { val preferredMonitor = System.getProperty("scenery.FullscreenMonitor", "0").toInt() val monitor = if (preferredMonitor == 0) { glfwGetPrimaryMonitor() } else { val monitors = glfwGetMonitors() if (monitors != null && monitors.remaining() >= preferredMonitor) { monitors.get(preferredMonitor) } else { glfwGetPrimaryMonitor() } } val hmd = hub.getWorkingHMDDisplay() if (hmd != null) { window.width = hmd.getRenderTargetSize().x().toInt() / 2 window.height = hmd.getRenderTargetSize().y().toInt() logger.info("Set fullscreen window dimensions to ${window.width}x${window.height}") } glfwSetWindowMonitor(window.window, monitor, 0, 0, window.width, window.height, GLFW_DONT_CARE) glfwSetInputMode(window.window, GLFW_CURSOR, GLFW_CURSOR_HIDDEN) swapchainRecreator.mustRecreate = true window.isFullscreen = true } } } /** * Embeds the swapchain into a [SceneryPanel]. Not supported by [VulkanSwapchain], * see [FXSwapchain] instead. */ override fun embedIn(panel: SceneryPanel?) { if(panel == null) { return } logger.error("Embedding is not supported with the default Vulkan swapchain. Use FXSwapchain instead.") } /** * Returns the number of fully presented frames. */ override fun presentedFrames(): Long { return presentedFrames } /** * Closes associated semaphores and fences. */ protected fun closeSyncPrimitives() { imageAvailableSemaphores.forEach { device.removeSemaphore(it) } imageAvailableSemaphores.clear() imageRenderedSemaphores.forEach { device.removeSemaphore(it) } imageRenderedSemaphores.clear() fences.forEach { VK10.vkDestroyFence(device.vulkanDevice, it, null) } fences.clear() imageUseFences.forEach { VK10.vkDestroyFence(device.vulkanDevice, it, null) } imageUseFences.clear() } /** * Closes the swapchain, deallocating all of its resources. */ override fun close() { vkQueueWaitIdle(presentQueue) vkQueueWaitIdle(queue) logger.debug("Closing swapchain $this") KHRSwapchain.vkDestroySwapchainKHR(device.vulkanDevice, handle, null) vkDestroySurfaceKHR(device.instance, surface, null) imageAvailableSemaphores.forEach { device.removeSemaphore(it) } imageAvailableSemaphores.clear() imageRenderedSemaphores.forEach { device.removeSemaphore(it) } imageRenderedSemaphores.clear() fences.forEach { vkDestroyFence(device.vulkanDevice, it, null) } fences.clear() imageUseFences.forEach { vkDestroyFence(device.vulkanDevice, it, null) } imageUseFences.clear() presentInfo.free() MemoryUtil.memFree(swapchainImage) MemoryUtil.memFree(swapchainPointer) windowSizeCallback.close() (window as SceneryWindow.GLFWWindow?)?.let { window -> glfwDestroyWindow(window.window) glfwTerminate() } } }
lgpl-3.0
5581f64b184cf6da50ad5829c1d040be
41.286624
174
0.619257
4.842451
false
false
false
false
dhis2/dhis2-android-sdk
core/src/main/java/org/hisp/dhis/android/core/parser/internal/expression/ExpressionState.kt
1
1829
/* * Copyright (c) 2004-2022, University of Oslo * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of the HISP project nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.hisp.dhis.android.core.parser.internal.expression internal class ExpressionState { var replaceNulls = true var itemsFound = 0 var itemValuesFound = 0 var itemZeroPosValuesFound = 0 var queryMods: QueryMods? = null }
bsd-3-clause
8e64c9611d3869622145f50dcfc7a69b
48.432432
83
0.763805
4.527228
false
false
false
false
nadraliev/DsrWeatherApp
app/src/main/java/soutvoid/com/DsrWeatherApp/ui/util/WeatherIconsHelper.kt
1
2647
package soutvoid.com.DsrWeatherApp.ui.util import com.mikepenz.weather_icons_typeface_library.WeatherIcons import soutvoid.com.DsrWeatherApp.ui.screen.weather.data.TimeOfDay import java.util.* object WeatherIconsHelper { /** * позволяет получить [WeatherIcons.Icon] по openweathermap id * в зависимости от текущего времени, времени заката и рассвета, возвращает разные иконки * @param [id] id погоды в openweathermap * @param [dt] время получения прогноза (обычно текущее время +- 10 мин) в секундах */ fun getWeatherIcon(id: Int, dt: Long, locale: Locale = Locale.getDefault()) : WeatherIcons.Icon { val calendar = Calendar.getInstance(locale) calendar.timeInMillis = dt * 1000 val timeOfDay = TimeOfDay.getByTime(calendar.get(Calendar.HOUR_OF_DAY)) val day: Boolean = timeOfDay == TimeOfDay.MORNING || timeOfDay == TimeOfDay.DAY if (day) return getDayWeatherIcon(id) else return getNightWeatherIcon(id) } /** * то же, что и [getWeatherIcon], но только дневные иконки */ fun getDayWeatherIcon(id : Int) : WeatherIcons.Icon { return WeatherIcons.Icon.valueOf("wic_owm_day_$id") } /** * то же, что и [getWeatherIcon], но только ночные иконки */ fun getNightWeatherIcon(id : Int) : WeatherIcons.Icon { return WeatherIcons.Icon.valueOf("wic_owm_night_$id") } /** * то же, что и [getWeatherIcon], но только нейтральные иконки */ fun getNeutralWeatherIcon(id : Int) : WeatherIcons.Icon { return WeatherIcons.Icon.valueOf("wic_owm_$id") } val windIcons = listOf<WeatherIcons.Icon>( WeatherIcons.Icon.wic_direction_down, WeatherIcons.Icon.wic_direction_down_left, WeatherIcons.Icon.wic_direction_right, WeatherIcons.Icon.wic_direction_up_left, WeatherIcons.Icon.wic_direction_up, WeatherIcons.Icon.wic_direction_up_right, WeatherIcons.Icon.wic_direction_left, WeatherIcons.Icon.wic_direction_down_right) /** * позволяет получить [WeatherIcons.Icon] для ветра в зависимости от направления ветра */ fun getDirectionalIcon(degrees: Double) : WeatherIcons.Icon { return windIcons[Math.round((degrees + 180) % 360 / 45).toInt() % 8] } }
apache-2.0
cf4942b615eb9f12b0fe748f07ef47b3
35.75
101
0.665674
3.373027
false
false
false
false
ogarcia/ultrasonic
core/subsonic-api-image-loader/src/main/kotlin/org/moire/ultrasonic/subsonic/loader/image/CoverArtRequestHandler.kt
2
1082
package org.moire.ultrasonic.subsonic.loader.image import com.squareup.picasso.Picasso.LoadedFrom.NETWORK import com.squareup.picasso.Request import com.squareup.picasso.RequestHandler import java.io.IOException import okio.Okio import org.moire.ultrasonic.api.subsonic.SubsonicAPIClient /** * Loads cover arts from subsonic api. */ class CoverArtRequestHandler(private val apiClient: SubsonicAPIClient) : RequestHandler() { override fun canHandleRequest(data: Request): Boolean { return with(data.uri) { scheme == SCHEME && authority == AUTHORITY && path == "/$COVER_ART_PATH" } } override fun load(request: Request, networkPolicy: Int): Result { val id = request.uri.getQueryParameter(QUERY_ID) ?: throw IllegalArgumentException("Nullable id") val response = apiClient.getCoverArt(id) if (response.hasError()) { throw IOException("${response.apiError}") } else { return Result(Okio.source(response.stream), NETWORK) } } }
gpl-3.0
62a2bfbcdfdd92dd82bdb3bccdedac91
31.787879
91
0.668207
4.643777
false
false
false
false
chrislo27/Tickompiler
src/main/kotlin/rhmodding/tickompiler/cli/DaemonCommand.kt
2
1808
package rhmodding.tickompiler.cli import picocli.CommandLine import rhmodding.tickompiler.Tickompiler import rhmodding.tickompiler.TickompilerCommand import java.util.regex.Pattern @CommandLine.Command(name = "daemon", description = ["Runs Tickompiler in daemon mode.", "This will provide a continuously running program which makes use of JIT (just-in-time compilation) to speed up future operations.", "You can optionally provide the first command you want to run as arguments to this command.", "CTRL+C will kill the program. Typing 'stop' or 'exit' will work too."], mixinStandardHelpOptions = true) class DaemonCommand : Runnable { @CommandLine.Parameters(index = "0", arity = "0..*", description = ["First command to execute along with its arguments, if any."]) var firstCommand: List<String> = listOf() override fun run() { println("Running in daemon mode: press CTRL+C or type 'stop' or 'exit' to terminate\nType '-h' for help\n${Tickompiler.VERSION}\n${Tickompiler.GITHUB}\n") var input: String = (if (firstCommand.isNotEmpty()) { // we have a first command to immediately execute firstCommand.joinToString(" ") } else readLine())?.trim() ?: return while (!input.equals("stop", true) && !input.equals("exit", true)) { if (input.isEmpty()) continue val list = mutableListOf<String>() val m = Pattern.compile("([^\"]\\S*|\".+?\")\\s*").matcher(input) while (m.find()) list.add(m.group(1).replace("\"", "")) Tickompiler.createAndParseCommandLine(TickompilerCommand(), *list.toTypedArray()) println("--------------------------------") input = readLine()?.trim() ?: return } } }
mit
836092dfd4057d0aa86bed58e890d686
41.069767
162
0.629425
4.453202
false
false
false
false
google/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/conversion/copy/ConvertTextJavaCopyPasteProcessor.kt
1
14723
// 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.conversion.copy import com.intellij.codeInsight.editorActions.CopyPastePostProcessor import com.intellij.codeInsight.editorActions.TextBlockTransferable import com.intellij.codeInsight.editorActions.TextBlockTransferableData import com.intellij.ide.highlighter.JavaFileType import com.intellij.openapi.diagnostic.ControlFlowException import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.RangeMarker import com.intellij.openapi.fileTypes.LanguageFileType import com.intellij.openapi.module.Module import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.project.DumbService import com.intellij.openapi.project.Project import com.intellij.openapi.util.Ref import com.intellij.psi.PsiDocumentManager import com.intellij.psi.PsiErrorElement import com.intellij.psi.PsiFile import com.intellij.psi.PsiFileFactory import com.intellij.refactoring.suggested.range import com.intellij.util.LocalTimeCounter import org.jetbrains.annotations.TestOnly import org.jetbrains.kotlin.asJava.toLightClass import org.jetbrains.kotlin.idea.base.util.module import org.jetbrains.kotlin.idea.KotlinFileType import org.jetbrains.kotlin.idea.editor.KotlinEditorOptions import org.jetbrains.kotlin.idea.statistics.ConversionType import org.jetbrains.kotlin.idea.statistics.J2KFusCollector import org.jetbrains.kotlin.idea.util.application.runWriteAction import org.jetbrains.kotlin.j2k.J2kConverterExtension import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.anyDescendantOfType import org.jetbrains.kotlin.psi.psiUtil.endOffset import org.jetbrains.kotlin.psi.psiUtil.getParentOfType import org.jetbrains.kotlin.utils.addToStdlib.ifNotEmpty import org.jetbrains.kotlin.utils.addToStdlib.safeAs import java.awt.datatransfer.DataFlavor import java.awt.datatransfer.Transferable import kotlin.system.measureTimeMillis class ConvertTextJavaCopyPasteProcessor : CopyPastePostProcessor<TextBlockTransferableData>() { private val LOG = Logger.getInstance(ConvertTextJavaCopyPasteProcessor::class.java) private val javaContextDeclarationRenderer = JavaContextDeclarationRenderer() private class MyTransferableData(val text: String) : TextBlockTransferableData { override fun getFlavor() = DATA_FLAVOR override fun getOffsetCount() = 0 override fun getOffsets(offsets: IntArray?, index: Int) = index override fun setOffsets(offsets: IntArray?, index: Int) = index companion object { val DATA_FLAVOR: DataFlavor = DataFlavor(ConvertTextJavaCopyPasteProcessor::class.java, "class: ConvertTextJavaCopyPasteProcessor") } } override fun collectTransferableData( file: PsiFile, editor: Editor, startOffsets: IntArray, endOffsets: IntArray ): List<TextBlockTransferableData> { if (file is KtFile) return listOf(CopiedKotlinCode(file.text, startOffsets, endOffsets)) return emptyList() } override fun extractTransferableData(content: Transferable): List<TextBlockTransferableData> { try { if (content.isDataFlavorSupported(DataFlavor.stringFlavor)) { if (content.isDataFlavorSupported(CopiedKotlinCode.DATA_FLAVOR) || /* Handled by ConvertJavaCopyPasteProcessor */ content.isDataFlavorSupported(CopiedJavaCode.DATA_FLAVOR) ) return emptyList() val text = content.getTransferData(DataFlavor.stringFlavor) as String return listOf(MyTransferableData(text)) } } catch (e: Throwable) { if (e is ControlFlowException) throw e LOG.error(e) } return emptyList() } override fun processTransferableData( project: Project, editor: Editor, bounds: RangeMarker, caretOffset: Int, indented: Ref<in Boolean>, values: List<TextBlockTransferableData> ) { if (DumbService.getInstance(project).isDumb) return if (!KotlinEditorOptions.getInstance().isEnableJavaToKotlinConversion) return //TODO: use another option? val text = TextBlockTransferable.convertLineSeparators(editor, (values.single() as MyTransferableData).text, values) val psiDocumentManager = PsiDocumentManager.getInstance(project) val targetFile = psiDocumentManager.getPsiFile(editor.document).safeAs<KtFile>()?.takeIf { it.virtualFile.isWritable } ?: return psiDocumentManager.commitDocument(editor.document) val useNewJ2k = checkUseNewJ2k(targetFile) val targetModule = targetFile.module val pasteTarget = detectPasteTarget(targetFile, bounds.startOffset, bounds.endOffset) ?: return val conversionContext = detectConversionContext(pasteTarget.pasteContext, text, project) ?: return if (!confirmConvertJavaOnPaste(project, isPlainText = true)) return val copiedJavaCode = prepareCopiedJavaCodeByContext(text, conversionContext, pasteTarget) val dataForConversion = DataForConversion.prepare(copiedJavaCode, project) fun convert() { val additionalImports = dataForConversion.tryResolveImports(targetFile) ProgressManager.checkCanceled() var convertedImportsText = additionalImports.convertCodeToKotlin(project, targetModule, useNewJ2k).text val convertedResult = dataForConversion.convertCodeToKotlin(project, targetModule, useNewJ2k) val convertedText = convertedResult.text ProgressManager.checkCanceled() val newBounds = runWriteAction { val importsInsertOffset = targetFile.importList?.endOffset ?: 0 if (targetFile.importDirectives.isEmpty() && importsInsertOffset > 0) convertedImportsText = "\n" + convertedImportsText if (convertedImportsText.isNotBlank()) editor.document.insertString(importsInsertOffset, convertedImportsText) val startOffset = bounds.startOffset editor.document.replaceString(startOffset, bounds.endOffset, convertedText) val endOffsetAfterCopy = startOffset + convertedText.length editor.caretModel.moveToOffset(endOffsetAfterCopy) editor.document.createRangeMarker(startOffset, startOffset + convertedText.length) } psiDocumentManager.commitAllDocuments() ProgressManager.checkCanceled() if (useNewJ2k) { val postProcessor = J2kConverterExtension.extension(useNewJ2k).createPostProcessor(formatCode = true) convertedResult.importsToAdd.forEach { fqName -> postProcessor.insertImport(targetFile, fqName) } } runPostProcessing(project, targetFile, newBounds.range, convertedResult.converterContext, useNewJ2k) conversionPerformed = true } val conversionTime = measureTimeMillis { convert() } J2KFusCollector.log( ConversionType.TEXT_EXPRESSION, checkUseNewJ2k(targetFile), conversionTime, dataForConversion.elementsAndTexts.linesCount(), filesCount = 1 ) } private fun DataForConversion.convertCodeToKotlin(project: Project, targetModule: Module?, useNewJ2k: Boolean): ConversionResult { return elementsAndTexts.convertCodeToKotlin(project, targetModule, useNewJ2k) } private val KtElement.pasteContext: KotlinContext get() = when (this) { is KtFile -> KotlinContext.TOP_LEVEL is KtClassBody -> KotlinContext.CLASS_BODY is KtBlockExpression -> KotlinContext.IN_BLOCK else -> KotlinContext.EXPRESSION } private fun detectPasteTarget(file: KtFile, startOffset: Int, endOffset: Int): KtElement? { if (isNoConversionPosition(file, startOffset)) return null val fileText = file.text val dummyDeclarationText = "fun dummy(){}" val newFileText = "${fileText.substring(0, startOffset)} $dummyDeclarationText\n${fileText.substring(endOffset)}" val newFile = parseAsFile(newFileText, KotlinFileType.INSTANCE, file.project) (newFile as KtFile).analysisContext = file val funKeyword = newFile.findElementAt(startOffset + 1) ?: return null if (funKeyword.node.elementType != KtTokens.FUN_KEYWORD) return null val declaration = funKeyword.parent as? KtFunction ?: return null return declaration.parent as? KtElement } private fun detectConversionContext(pasteContext: KotlinContext, text: String, project: Project): JavaContext? { if (isParsedAsKotlinCode(text, pasteContext, project)) return null fun JavaContext.check(): JavaContext? = takeIf { isParsedAsJavaCode(text, it, project) } when (pasteContext) { KotlinContext.TOP_LEVEL -> { JavaContext.TOP_LEVEL.check()?.let { return it } JavaContext.CLASS_BODY.check()?.let { return it } return null } KotlinContext.CLASS_BODY -> return JavaContext.CLASS_BODY.check() KotlinContext.IN_BLOCK -> return JavaContext.IN_BLOCK.check() KotlinContext.EXPRESSION -> return JavaContext.EXPRESSION.check() } } private enum class KotlinContext { TOP_LEVEL, CLASS_BODY, IN_BLOCK, EXPRESSION } private enum class JavaContext { TOP_LEVEL, CLASS_BODY, IN_BLOCK, EXPRESSION } private fun isParsedAsJavaCode(text: String, context: JavaContext, project: Project): Boolean { return when (context) { JavaContext.TOP_LEVEL -> isParsedAsJavaFile(text, project) JavaContext.CLASS_BODY -> isParsedAsJavaFile("class Dummy { $text\n}", project) JavaContext.IN_BLOCK -> isParsedAsJavaFile("class Dummy { void foo() {$text\n}\n}", project) JavaContext.EXPRESSION -> isParsedAsJavaFile("class Dummy { Object field = $text; }", project) } } private fun isParsedAsKotlinCode(text: String, context: KotlinContext, project: Project): Boolean { return when (context) { KotlinContext.TOP_LEVEL -> isParsedAsKotlinFile(text, project) KotlinContext.CLASS_BODY -> isParsedAsKotlinFile("class Dummy { $text\n}", project) KotlinContext.IN_BLOCK -> isParsedAsKotlinFile("fun foo() {$text\n}", project) KotlinContext.EXPRESSION -> isParsedAsKotlinFile("val v = $text", project) } } private fun isParsedAsJavaFile(text: String, project: Project) = isParsedAsFile(text, JavaFileType.INSTANCE, project) private fun isParsedAsKotlinFile(text: String, project: Project) = isParsedAsFile(text, KotlinFileType.INSTANCE, project) private fun isParsedAsFile(text: String, fileType: LanguageFileType, project: Project): Boolean { val psiFile = parseAsFile(text, fileType, project) return !psiFile.anyDescendantOfType<PsiErrorElement>() } private fun parseAsFile(text: String, fileType: LanguageFileType, project: Project): PsiFile { return PsiFileFactory.getInstance(project) .createFileFromText("Dummy." + fileType.defaultExtension, fileType, text, LocalTimeCounter.currentTime(), true) } private fun DataForConversion.tryResolveImports(targetFile: KtFile): ElementAndTextList { val importResolver = PlainTextPasteImportResolver(this, targetFile) importResolver.addImportsFromTargetFile() importResolver.tryResolveReferences() return ElementAndTextList(importResolver.addedImports.flatMap { importStatement -> listOf("\n", importStatement) } + "\n\n") //TODO Non-manual formatting for import list } private fun prepareCopiedJavaCodeByContext(text: String, context: JavaContext, target: KtElement): CopiedJavaCode { val targetFile = target.containingFile as KtFile val (localDeclarations, memberDeclarations) = javaContextDeclarationRenderer.render(target) val prefix = buildString { targetFile.packageDirective?.let { if (it.text.isNotEmpty()) { append(it.text) append(";\n") } } } val classDef = when (context) { JavaContext.TOP_LEVEL -> "" JavaContext.CLASS_BODY, JavaContext.IN_BLOCK, JavaContext.EXPRESSION -> { val lightClass = target.getParentOfType<KtClass>(false)?.toLightClass() buildString { append("class ") append(lightClass?.name ?: "Dummy") lightClass?.extendsListTypes?.ifNotEmpty { joinTo( this@buildString, prefix = " extends " ) { it.getCanonicalText(true) } } lightClass?.implementsListTypes?.ifNotEmpty { joinTo(this@buildString, prefix = " implements ") { it.getCanonicalText( true ) } } } } } return when (context) { JavaContext.TOP_LEVEL -> createCopiedJavaCode(prefix, "$", text) JavaContext.CLASS_BODY -> createCopiedJavaCode(prefix, "$classDef {\n$memberDeclarations $\n}", text) JavaContext.IN_BLOCK -> createCopiedJavaCode(prefix, "$classDef {\n$memberDeclarations void foo() {\n$localDeclarations $\n}\n}", text) JavaContext.EXPRESSION -> createCopiedJavaCode(prefix, "$classDef {\nObject field = $\n}", text) } } private fun createCopiedJavaCode(prefix: String, templateWithoutPrefix: String, text: String): CopiedJavaCode { val template = "$prefix$templateWithoutPrefix" val index = template.indexOf("$") assert(index >= 0) val fileText = template.substring(0, index) + text + template.substring(index + 1) return CopiedJavaCode(fileText, intArrayOf(index), intArrayOf(index + text.length)) } companion object { @get:TestOnly var conversionPerformed: Boolean = false } }
apache-2.0
4f38678707173e411ba3c1e60c883a19
43.75076
158
0.68016
5.075147
false
false
false
false
google/iosched
shared/src/main/java/com/google/samples/apps/iosched/shared/fcm/IoschedFirebaseMessagingService.kt
3
3304
/* * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.samples.apps.iosched.shared.fcm import android.app.job.JobInfo import android.app.job.JobScheduler import android.app.job.JobScheduler.RESULT_FAILURE import android.app.job.JobScheduler.RESULT_SUCCESS import android.content.ComponentName import android.content.Context import com.google.firebase.messaging.FirebaseMessagingService import com.google.firebase.messaging.RemoteMessage import com.google.samples.apps.iosched.shared.data.job.ConferenceDataService import timber.log.Timber import java.util.concurrent.TimeUnit /** * Receives Firebase Cloud Messages and starts a [ConferenceDataService] to download new data. */ class IoschedFirebaseMessagingService : FirebaseMessagingService() { override fun onNewToken(token: String) { super.onNewToken(token) Timber.d("New firebase token: $token") // Nothing to do, we update the user's firebase token via FirebaseAuthStateUserDataSource } override fun onMessageReceived(remoteMessage: RemoteMessage) { Timber.d("Message data payload: ${remoteMessage.data}") val data = remoteMessage.data if (data[TRIGGER_EVENT_DATA_SYNC_key] == TRIGGER_EVENT_DATA_SYNC) { // Schedule job on JobScheduler when FCM message with action `TRIGGER_EVENT_DATA_SYNC` // is received. scheduleFetchEventData() } } private fun scheduleFetchEventData() { val serviceComponent = ComponentName(this, ConferenceDataService::class.java) val builder = JobInfo.Builder(ConferenceDataService.JOB_ID, serviceComponent) .setMinimumLatency(MINIMUM_LATENCY) // wait at least .setRequiredNetworkType(JobInfo.NETWORK_TYPE_UNMETERED) // Unmetered if possible .setOverrideDeadline(OVERRIDE_DEADLINE) // run by deadline if conditions not met val jobScheduler = getSystemService(Context.JOB_SCHEDULER_SERVICE) as JobScheduler val result = jobScheduler.schedule(builder.build()) if (result == RESULT_FAILURE) { Timber.e( "Invalid param supplied to JobScheduler when starting ConferenceDataService job." ) } else if (result == RESULT_SUCCESS) { Timber.i("ConferenceDataService job scheduled..") } } companion object { private const val TRIGGER_EVENT_DATA_SYNC = "SYNC_EVENT_DATA" private const val TRIGGER_EVENT_DATA_SYNC_key = "action" // Some latency to avoid load spikes private val MINIMUM_LATENCY = TimeUnit.SECONDS.toMillis(5) // Job scheduled to run only with Wi-Fi but with a deadline private val OVERRIDE_DEADLINE = TimeUnit.MINUTES.toMillis(15) } }
apache-2.0
971f67b830822e3f1d005ea956a47c3a
39.292683
98
0.715194
4.588889
false
false
false
false
apollographql/apollo-android
apollo-compiler/src/main/kotlin/com/apollographql/apollo3/compiler/codegen/java/file/OperationSelectionsBuilder.kt
1
1550
package com.apollographql.apollo3.compiler.codegen.java.file import com.apollographql.apollo3.ast.GQLFragmentDefinition import com.apollographql.apollo3.ast.Schema import com.apollographql.apollo3.compiler.codegen.java.CodegenJavaFile import com.apollographql.apollo3.compiler.codegen.java.JavaClassBuilder import com.apollographql.apollo3.compiler.codegen.java.JavaContext import com.apollographql.apollo3.compiler.codegen.java.selections.CompiledSelectionsBuilder import com.apollographql.apollo3.compiler.ir.IrOperation import com.squareup.javapoet.ClassName class OperationSelectionsBuilder( val context: JavaContext, val operation: IrOperation, val schema: Schema, val allFragmentDefinitions: Map<String, GQLFragmentDefinition>, ) : JavaClassBuilder { private val packageName = context.layout.operationResponseFieldsPackageName(operation.filePath) private val simpleName = context.layout.operationSelectionsName(operation) override fun prepare() { context.resolver.registerOperationSelections( operation.name, ClassName.get(packageName, simpleName) ) } override fun build(): CodegenJavaFile { return CodegenJavaFile( packageName = packageName, typeSpec = CompiledSelectionsBuilder( context = context, allFragmentDefinitions = allFragmentDefinitions, schema = schema ).build( selections = operation.selections, rootName = simpleName, parentType = operation.typeCondition ) ) } }
mit
679f3c63293ec8e520f386e67083b160
35.928571
97
0.758065
4.84375
false
false
false
false
apollographql/apollo-android
apollo-compiler/src/main/kotlin/com/apollographql/apollo3/compiler/codegen/java/adapter/EnumAdapterBuilder.kt
1
3517
package com.apollographql.apollo3.compiler.codegen.java.adapter import com.apollographql.apollo3.compiler.codegen.Identifier import com.apollographql.apollo3.compiler.codegen.Identifier.customScalarAdapters import com.apollographql.apollo3.compiler.codegen.Identifier.rawValue import com.apollographql.apollo3.compiler.codegen.Identifier.reader import com.apollographql.apollo3.compiler.codegen.Identifier.safeValueOf import com.apollographql.apollo3.compiler.codegen.Identifier.toJson import com.apollographql.apollo3.compiler.codegen.Identifier.value import com.apollographql.apollo3.compiler.codegen.Identifier.writer import com.apollographql.apollo3.compiler.codegen.java.CodegenJavaFile import com.apollographql.apollo3.compiler.codegen.java.JavaClassBuilder import com.apollographql.apollo3.compiler.codegen.java.JavaClassNames import com.apollographql.apollo3.compiler.codegen.java.JavaContext import com.apollographql.apollo3.compiler.codegen.java.T import com.apollographql.apollo3.compiler.ir.IrEnum import com.squareup.javapoet.ClassName import com.squareup.javapoet.CodeBlock import com.squareup.javapoet.MethodSpec import com.squareup.javapoet.ParameterizedTypeName import com.squareup.javapoet.TypeName import com.squareup.javapoet.TypeSpec import javax.lang.model.element.Modifier class EnumResponseAdapterBuilder( val context: JavaContext, val enum: IrEnum, ) : JavaClassBuilder { private val layout = context.layout private val packageName = layout.typeAdapterPackageName() private val simpleName = layout.enumResponseAdapterName(enum.name) override fun prepare() { context.resolver.registerEnumAdapter( enum.name, ClassName.get(packageName, simpleName) ) } override fun build(): CodegenJavaFile { return CodegenJavaFile( packageName = packageName, typeSpec = enum.typeSpec() ) } private fun IrEnum.typeSpec(): TypeSpec { val adaptedTypeName = context.resolver.resolveSchemaType(enum.name) val fromResponseMethodSpec = MethodSpec.methodBuilder(Identifier.fromJson) .addModifiers(Modifier.PUBLIC) .addException(JavaClassNames.IOException) .addAnnotation(JavaClassNames.Override) .addParameter(JavaClassNames.JsonReader, reader) .addParameter(JavaClassNames.CustomScalarAdapters, customScalarAdapters) .returns(adaptedTypeName) .addCode( CodeBlock.builder() .addStatement("String $rawValue = reader.nextString()") .addStatement("return $T.$safeValueOf($rawValue)", adaptedTypeName) .build() ) .build() val toResponseMethodSpec = toResponseMethodSpecBuilder(adaptedTypeName) .addCode("$writer.$value($value.rawValue);\n") .build() return TypeSpec.enumBuilder(layout.enumResponseAdapterName(name)) .addModifiers(Modifier.PUBLIC) .addEnumConstant("INSTANCE") .addSuperinterface(ParameterizedTypeName.get(JavaClassNames.Adapter, adaptedTypeName)) .addMethod(fromResponseMethodSpec) .addMethod(toResponseMethodSpec) .build() } } internal fun toResponseMethodSpecBuilder(typeName: TypeName) = MethodSpec.methodBuilder(toJson) .addModifiers(Modifier.PUBLIC) .addException(JavaClassNames.IOException) .addAnnotation(JavaClassNames.Override) .addParameter(JavaClassNames.JsonWriter, writer) .addParameter(JavaClassNames.CustomScalarAdapters, customScalarAdapters) .addParameter(typeName, value)
mit
ad684ed4d738371a7aa418513d8e17ec
41.385542
95
0.773955
4.720805
false
false
false
false
sakki54/RLGdx
src/main/kotlin/com/brekcel/RLGdx/misc/Direction.kt
1
1775
//=====Copyright 2017 Clayton Breckel=====// package com.brekcel.RLGdx.misc /** Simple enum to store a direction */ enum class Direction { /** No direction (0,0) */ ZERO { override fun getXY() = Pair(0, 0) }, /** Upwards direction (0,1) */ UP { override fun getXY() = Pair(0, 1) }, /** Down direction (0,-1) */ DOWN { override fun getXY() = Pair(0, -1) }, /** Right direction (1,0)*/ RIGHT { override fun getXY() = Pair(1, 0) }, /** Left direction (-1,0) */ LEFT { override fun getXY() = Pair(-1, 0) }, /** Up and to the right direction (1,1) */ UP_RIGHT { override fun getXY() = Pair(1, 1) }, /** Up and to the left direction (-1,1) */ UP_LEFT { override fun getXY() = Pair(-1, 1) }, /** Down and to the right direction (1,-1) */ DOWN_RIGHT { override fun getXY() = Pair(1, -1) }, /** Down and to the left direction (-1,-1) */ DOWN_LEFT { override fun getXY() = Pair(-1, -1) }; /** Converts the enum into x,y coords */ abstract fun getXY(): Pair<Int, Int> /** Returns a Pair with 0 for the x, and y for the y */ fun StripX() = Pair(0, getXY().second) /** Returns a Pair with x for the x, and 0 for the y */ fun StripY() = Pair(getXY().first, 0) /** Static companion object */ companion object { /** Get's an enum based off of the given direction */ @JvmStatic fun getEnum(x: Int, y: Int): Direction { when (x) { -1 -> when (y) { -1 -> return DOWN_LEFT 0 -> return LEFT 1 -> return UP_LEFT } 0 -> when (y) { -1 -> return DOWN 0 -> return ZERO 1 -> return UP } 1 -> when (y) { -1 -> return DOWN_RIGHT 0 -> return RIGHT 1 -> return UP_RIGHT } } throw IllegalArgumentException("x and y must be -1<=i<=1. X was $x, Y was $y") } } }
mit
82d6e8834de31ca20b10c6b2aa8cf81a
21.75641
81
0.56169
2.769111
false
false
false
false
StepicOrg/stepik-android
app/src/main/java/org/stepik/android/view/course_purchase/delegate/PromoCodeViewDelegate.kt
1
7449
package org.stepik.android.view.course_purchase.delegate import android.graphics.drawable.AnimationDrawable import android.graphics.drawable.Drawable import android.graphics.drawable.LayerDrawable import android.graphics.drawable.RippleDrawable import android.text.Editable import androidx.appcompat.content.res.AppCompatResources import androidx.core.view.isVisible import androidx.core.widget.doAfterTextChanged import org.stepic.droid.R import org.stepic.droid.databinding.BottomSheetDialogCoursePurchaseBinding import org.stepik.android.presentation.course_purchase.CoursePurchaseFeature import org.stepik.android.presentation.course_purchase.CoursePurchaseFeature.PromoCodeState import org.stepik.android.presentation.course_purchase.CoursePurchaseViewModel import org.stepik.android.view.step_quiz_choice.ui.delegate.LayerListDrawableDelegate import ru.nobird.android.view.base.ui.extension.getDrawableCompat import ru.nobird.android.view.base.ui.extension.setTextIfChanged class PromoCodeViewDelegate( coursePurchaseBinding: BottomSheetDialogCoursePurchaseBinding, private val coursePurchaseViewModel: CoursePurchaseViewModel ) { companion object { private const val EVALUATION_FRAME_DURATION_MS = 250 } private val context = coursePurchaseBinding.root.context private val coursePromoCodeAction = coursePurchaseBinding.coursePromoCodeAction private val coursePromoCodeContainer = coursePurchaseBinding.coursePurchasePromoCodeInputContainer private val coursePromoCodeInput = coursePurchaseBinding.coursePurchasePromoCodeInput private val coursePromoCodeDismiss = coursePurchaseBinding.coursePurchasePromoCodeInputDismiss private val coursePromoCodeSubmitAction = coursePurchaseBinding.coursePurchasePromoCodeSubmitAction private val coursePurchasePromoCodeResultMessage = coursePurchaseBinding.coursePurchasePromoCodeResultMessage private val layerListDrawableDelegate = LayerListDrawableDelegate( listOf( R.id.idle_state, R.id.loading_state, R.id.invalid_state, R.id.valid_state ), (coursePromoCodeSubmitAction.background as RippleDrawable).findDrawableByLayerId(R.id.promo_code_layer_list) as LayerDrawable ) private var promoCodeState: PromoCodeState = PromoCodeState.Idle init { coursePromoCodeAction.setOnClickListener { coursePurchaseViewModel.onNewMessage(CoursePurchaseFeature.Message.HavePromoCodeMessage) } coursePromoCodeInput.doAfterTextChanged { text: Editable? -> val length = text?.length ?: 0 coursePromoCodeDismiss.isVisible = length != 0 coursePromoCodeSubmitAction.isVisible = length != 0 if ((promoCodeState as? PromoCodeState.Valid)?.text == text.toString()) { return@doAfterTextChanged } coursePurchaseViewModel.onNewMessage(CoursePurchaseFeature.Message.PromoCodeEditingMessage) } coursePromoCodeDismiss.setOnClickListener { coursePromoCodeInput.setText("") } coursePromoCodeSubmitAction.setOnClickListener { coursePurchaseViewModel.onNewMessage(CoursePurchaseFeature.Message.PromoCodeCheckMessage(coursePromoCodeInput.text.toString())) } } fun setViewVisibility(isVisible: Boolean) { coursePromoCodeAction.isVisible = isVisible coursePromoCodeContainer.isVisible = isVisible coursePromoCodeInput.isVisible = isVisible coursePromoCodeDismiss.isVisible = isVisible coursePromoCodeSubmitAction.isVisible = isVisible coursePurchasePromoCodeResultMessage.isVisible = isVisible } fun render(state: PromoCodeState) { this.promoCodeState = state coursePromoCodeAction.isVisible = state is PromoCodeState.Idle coursePromoCodeContainer.isVisible = state !is PromoCodeState.Idle coursePromoCodeDismiss.isEnabled = state !is PromoCodeState.Checking coursePromoCodeSubmitAction.isEnabled = state is PromoCodeState.Editing coursePromoCodeInput.isEnabled = state !is PromoCodeState.Checking coursePurchasePromoCodeResultMessage.isVisible = state is PromoCodeState.Checking || state is PromoCodeState.Valid || state is PromoCodeState.Invalid val (messageRes, colorRes) = getPromoCodeResultMessage(state) if (messageRes != -1 && colorRes != -1) { coursePurchasePromoCodeResultMessage.text = context.getString(messageRes) coursePurchasePromoCodeResultMessage.setTextColor(AppCompatResources.getColorStateList(context, colorRes)) } coursePromoCodeSubmitAction.setImageDrawable(getDrawableForSubmitAction(state)) setEditTextFromState(state) layerListDrawableDelegate.showLayer(getBackgroundLayer(state)) } private fun getPromoCodeResultMessage(promoCodeState: PromoCodeState): Pair<Int, Int> = when (promoCodeState) { is PromoCodeState.Idle, is PromoCodeState.Editing -> -1 to -1 is PromoCodeState.Checking -> R.string.course_purchase_promocode_checking to R.color.color_overlay_violet is PromoCodeState.Valid -> R.string.course_purchase_promocode_valid to R.color.color_overlay_green is PromoCodeState.Invalid -> R.string.course_purchase_promocode_invalid to R.color.color_overlay_red } private fun setEditTextFromState(state: PromoCodeState) { when (state) { is PromoCodeState.Checking -> { coursePromoCodeInput.setTextIfChanged(state.text) } is PromoCodeState.Valid -> coursePromoCodeInput.setTextIfChanged(state.text) else -> return } } private fun getDrawableForSubmitAction(state: PromoCodeState): Drawable? = when (state) { is PromoCodeState.Idle, is PromoCodeState.Editing -> AppCompatResources.getDrawable(context, R.drawable.ic_arrow_forward) is PromoCodeState.Checking -> { val evaluationDrawable = AnimationDrawable() evaluationDrawable.addFrame(context.getDrawableCompat(R.drawable.ic_step_quiz_evaluation_frame_1), EVALUATION_FRAME_DURATION_MS) evaluationDrawable.addFrame(context.getDrawableCompat(R.drawable.ic_step_quiz_evaluation_frame_2), EVALUATION_FRAME_DURATION_MS) evaluationDrawable.addFrame(context.getDrawableCompat(R.drawable.ic_step_quiz_evaluation_frame_3), EVALUATION_FRAME_DURATION_MS) evaluationDrawable.isOneShot = false evaluationDrawable.start() evaluationDrawable } is PromoCodeState.Invalid -> AppCompatResources.getDrawable(context, R.drawable.ic_step_quiz_wrong) is PromoCodeState.Valid -> AppCompatResources.getDrawable(context, R.drawable.ic_step_quiz_correct) } private fun getBackgroundLayer(state: PromoCodeState): Int = when (state) { is PromoCodeState.Idle, is PromoCodeState.Editing -> R.id.idle_state is PromoCodeState.Checking -> R.id.loading_state is PromoCodeState.Invalid -> R.id.invalid_state is PromoCodeState.Valid -> R.id.valid_state } }
apache-2.0
96729c29b5a6a7830ca0edb461f072d1
47.69281
186
0.722513
4.956088
false
false
false
false
OpenASR/idear
src/main/java/org/openasr/idear/nlp/Commands.kt
2
1153
package org.openasr.idear.nlp object Commands { const val OPEN = "open" const val SETTINGS = "settings" const val RECENT = "recent" const val TERMINAL = "terminal" const val FOCUS = "focus" const val EDITOR = "editor" const val PROJECT = "project" const val SELECTION = "selection" const val EXPAND = "grow" const val SHRINK = "shrink" const val PRESS = "press" const val DELETE = "delete" const val DEBUG = "debug" const val ENTER = "enter" const val ESCAPE = "escape" const val TAB = "tab" const val UNDO = "undo" const val NEXT = "next" const val LINE = "line" const val PAGE = "page" const val METHOD = "method" const val PREVIOUS = "previous" const val INSPECT_CODE = "inspect code" const val OKAY_GOOGLE = "okay google" const val OK_GOOGLE = "ok google" const val OKAY_IDEA = "okay idea" const val OK_IDEA = "ok idea" const val HI_IDEA = "hi idea" const val WHERE_AM_I = "where am i" const val NAVIGATE = "navigate" const val EXECUTE = "execute" const val GOTO = "goto line" const val SHOW_USAGES = "show usages" }
apache-2.0
fef6b6e25802fe31a043edb304feef9c
30.189189
43
0.630529
3.625786
false
false
false
false
mrlem/happy-cows
core/src/org/mrlem/happycows/ui/actors/HorizonActor.kt
1
1490
package org.mrlem.happycows.ui.actors import com.badlogic.gdx.graphics.Texture.TextureFilter import com.badlogic.gdx.graphics.g2d.Batch import com.badlogic.gdx.graphics.g2d.TextureRegion import com.badlogic.gdx.scenes.scene2d.Actor import org.mrlem.happycows.ui.caches.TextureCache /** * @author Sébastien Guillemin <[email protected]> */ class HorizonActor : Actor() { private var skyTextureRegion: TextureRegion private var groundTextureRegion: TextureRegion init { var texture = TextureCache.instance[TextureCache.SKY_TEXTURE_ID]!! texture.setFilter(TextureFilter.Nearest, TextureFilter.Linear) skyTextureRegion = TextureRegion(texture) texture = TextureCache.instance[TextureCache.GROUND_TEXTURE_ID]!! texture.setFilter(TextureFilter.Nearest, TextureFilter.Linear) groundTextureRegion = TextureRegion(texture) width = texture.width.toFloat() height = texture.height.toFloat() } override fun draw(batch: Batch, parentAlpha: Float) { batch.setColor(color.r, color.g, color.b, color.a * parentAlpha) batch.begin() batch.draw(skyTextureRegion, x, y + height / HORIZON_LEVEL, originX, originY, width, height - height / HORIZON_LEVEL, scaleX, scaleY, rotation) batch.draw(groundTextureRegion, x, y, originX, originY, width, height / HORIZON_LEVEL, scaleX, scaleY, rotation) batch.end() } companion object { const val HORIZON_LEVEL = 2.5f } }
gpl-3.0
12e2f6a3085e0638fa29be55d872fc27
36.225
151
0.715917
4.002688
false
false
false
false
code-helix/slatekit
src/lib/kotlin/slatekit-common/src/main/kotlin/slatekit/common/NOTE.kt
1
2596
/** * <slate_header> * url: www.slatekit.com * git: www.github.com/code-helix/slatekit * org: www.codehelix.co * author: Kishore Reddy * copyright: 2016 CodeHelix Solutions Inc. * license: refer to website and/or github * about: A tool-kit, utility library and server-backend * mantra: Simplicity above all else * </slate_header> */ package slatekit.common /** * Similar to @see[kotlin.TODO] but a type-safe way to track Notes, and this does not throw exceptions */ object NOTE { private var logger: ((String) -> Unit)? = null /** * sets the logger for messages */ @JvmStatic fun CONFIGURE(logger: ((String) -> Unit)?) { NOTE.logger = logger } /** * Indicates that code should be removed at some point * @param tag * @param msg * @param callback */ @JvmStatic fun REMOVE(tag: String = "", msg: String = "", callback: (() -> Unit)? = null) { exec("NOTE.REMOVE: $msg", tag, callback) } /** * Indicates that an implementation is required * @param tag * @param msg * @param callback */ @JvmStatic fun IMPLEMENT(tag: String = "", msg: String = "", callback: (() -> Unit)? = null) { exec("NOTE.IMPLEMENT: $msg", tag, callback) } /** * Indicates that an improvement is required * @param tag * @param msg * @param callback */ @JvmStatic fun IMPROVE(tag: String = "", msg: String = "", callback: (() -> Unit)? = null) { exec("NOTE.IMPROVE: $msg", tag, callback) } /** * Indicates that a refactoring is required * @param tag * @param msg * @param callback */ @JvmStatic fun REFACTOR(tag: String = "", msg: String = "", callback: (() -> Unit)? = null) { exec("NOTE.REFACTOR: $msg", tag, callback) } /** * Indicates a bug/potential bug * @param tag * @param msg * @param bugId * @param callback */ @JvmStatic fun BUG(tag: String = "", msg: String = "", bugId: String = "", callback: (() -> Unit)? = null) { exec("NOTE.BUG: $bugId - $msg", tag, callback) } /** * Indicates a reference to a specific work ticket ( e.g. JIRA ) * @param id * @param msg * @param callback */ @JvmStatic fun TICKET(id: String = "", msg: String = "", callback: (() -> Unit)? = null) { exec("NOTE.TICKET: $msg", id, callback) } private fun exec(msg: String, tag: String, callback: (() -> Unit)? = null) { logger?.let { log -> log("$tag:$msg") } callback?.invoke() } }
apache-2.0
6891044204343fcf43cdc16e41bd901a
26.326316
112
0.558166
3.812041
false
false
false
false
DanielMartinus/Konfetti
samples/shared/src/main/java/nl/dionsegijn/samples/shared/Presets.kt
1
3583
package nl.dionsegijn.samples.shared import nl.dionsegijn.konfetti.core.Angle import nl.dionsegijn.konfetti.core.Party import nl.dionsegijn.konfetti.core.Position import nl.dionsegijn.konfetti.core.Rotation import nl.dionsegijn.konfetti.core.Spread import nl.dionsegijn.konfetti.core.emitter.Emitter import nl.dionsegijn.konfetti.core.models.Size import java.util.concurrent.TimeUnit class Presets { companion object { fun festive(): List<Party> { val party = Party( speed = 30f, maxSpeed = 50f, damping = 0.9f, angle = Angle.TOP, spread = 45, size = listOf(Size.SMALL, Size.LARGE), timeToLive = 3000L, rotation = Rotation(), colors = listOf(0xfce18a, 0xff726d, 0xf4306d, 0xb48def), emitter = Emitter(duration = 100, TimeUnit.MILLISECONDS).max(30), position = Position.Relative(0.5, 1.0) ) return listOf( party, party.copy( speed = 55f, maxSpeed = 65f, spread = 10, emitter = Emitter(duration = 100, TimeUnit.MILLISECONDS).max(10), ), party.copy( speed = 50f, maxSpeed = 60f, spread = 120, emitter = Emitter(duration = 100, TimeUnit.MILLISECONDS).max(40), ), party.copy( speed = 65f, maxSpeed = 80f, spread = 10, emitter = Emitter(duration = 100, TimeUnit.MILLISECONDS).max(10), ) ) } fun explode(): List<Party> { return listOf( Party( speed = 0f, maxSpeed = 30f, damping = 0.9f, spread = 360, colors = listOf(0xfce18a, 0xff726d, 0xf4306d, 0xb48def), emitter = Emitter(duration = 100, TimeUnit.MILLISECONDS).max(100), position = Position.Relative(0.5, 0.3) ) ) } fun parade(): List<Party> { val party = Party( speed = 10f, maxSpeed = 30f, damping = 0.9f, angle = Angle.RIGHT - 45, spread = Spread.SMALL, colors = listOf(0xfce18a, 0xff726d, 0xf4306d, 0xb48def), emitter = Emitter(duration = 5, TimeUnit.SECONDS).perSecond(30), position = Position.Relative(0.0, 0.5) ) return listOf( party, party.copy( angle = party.angle - 90, // flip angle from right to left position = Position.Relative(1.0, 0.5) ), ) } fun rain(): List<Party> { return listOf( Party( speed = 0f, maxSpeed = 15f, damping = 0.9f, angle = Angle.BOTTOM, spread = Spread.ROUND, colors = listOf(0xfce18a, 0xff726d, 0xf4306d, 0xb48def), emitter = Emitter(duration = 5, TimeUnit.SECONDS).perSecond(100), position = Position.Relative(0.0, 0.0).between(Position.Relative(1.0, 0.0)) ) ) } } }
isc
d7427b7847a87327b45d5879c97d3422
34.127451
95
0.459112
4.518285
false
false
false
false
benoitletondor/EasyBudget
Android/EasyBudget/app/src/main/java/com/benoitletondor/easybudgetapp/view/settings/PreferencesFragment.kt
1
27476
/* * Copyright 2022 Benoit LETONDOR * * 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.benoitletondor.easybudgetapp.view.settings import android.Manifest import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.content.IntentFilter import android.content.pm.PackageManager import android.content.res.Configuration import android.net.Uri import android.os.Build import android.os.Bundle import android.view.View import android.view.WindowManager import android.widget.EditText import android.widget.Toast import androidx.activity.result.ActivityResultLauncher import androidx.activity.result.contract.ActivityResultContracts import androidx.appcompat.app.AppCompatDelegate import androidx.core.app.ActivityCompat import androidx.core.content.ContextCompat import androidx.localbroadcastmanager.content.LocalBroadcastManager import androidx.preference.* import com.benoitletondor.easybudgetapp.BuildConfig import com.benoitletondor.easybudgetapp.R import com.benoitletondor.easybudgetapp.helper.* import com.benoitletondor.easybudgetapp.iab.INTENT_IAB_STATUS_CHANGED import com.benoitletondor.easybudgetapp.iab.Iab import com.benoitletondor.easybudgetapp.parameters.* import com.benoitletondor.easybudgetapp.view.RatingPopup import com.benoitletondor.easybudgetapp.view.settings.SettingsActivity.Companion.USER_GONE_PREMIUM_INTENT import com.benoitletondor.easybudgetapp.view.main.MainActivity import com.benoitletondor.easybudgetapp.view.premium.PremiumActivity import com.benoitletondor.easybudgetapp.view.selectcurrency.SelectCurrencyFragment import com.benoitletondor.easybudgetapp.view.settings.SettingsActivity.Companion.SHOW_BACKUP_INTENT_KEY import com.benoitletondor.easybudgetapp.view.settings.backup.BackupSettingsActivity import com.google.android.material.dialog.MaterialAlertDialogBuilder import com.roomorama.caldroid.CaldroidFragment import dagger.hilt.android.AndroidEntryPoint import java.net.URLEncoder import javax.inject.Inject /** * Fragment to display preferences * * @author Benoit LETONDOR */ @AndroidEntryPoint class PreferencesFragment : PreferenceFragmentCompat() { /** * The dialog to select a new currency (will be null if not shown) */ private var selectCurrencyDialog: SelectCurrencyFragment? = null /** * Broadcast receiver (used for currency selection) */ private lateinit var receiver: BroadcastReceiver /** * Category containing premium features (shown to premium users) */ private lateinit var premiumCategory: PreferenceCategory /** * Category containing ways to become premium (shown to not premium users) */ private lateinit var notPremiumCategory: PreferenceCategory /** * Launcher for notification permission request */ private lateinit var notificationRequestPermissionLauncher: ActivityResultLauncher<String> /** * Is the premium category shown */ private var premiumShown = true /** * Is the not premium category shown */ private var notPremiumShown = true @Inject lateinit var iab: Iab @Inject lateinit var parameters: Parameters // ----------------------------------------> override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) { setPreferencesFromResource(R.xml.preferences, rootKey) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) notificationRequestPermissionLauncher = registerForActivityResult(ActivityResultContracts.RequestPermission()) { granted -> if (!granted) { activity?.let { MaterialAlertDialogBuilder(it) .setTitle(R.string.setting_notification_permission_rejected_dialog_title) .setMessage(R.string.setting_notification_permission_rejected_dialog_description) .setPositiveButton(R.string.setting_notification_permission_rejected_dialog_accept_cta) { dialog, _ -> dialog.dismiss() showNotificationPermissionIfNeeded() } .setNegativeButton(R.string.setting_notification_permission_rejected_dialog_not_now_cta) { dialog, _ -> dialog.dismiss() } .show() } } } /* * Rating button */ findPreference<Preference>(resources.getString(R.string.setting_category_rate_button_key))?.onPreferenceClickListener = Preference.OnPreferenceClickListener { activity?.let { activity -> RatingPopup(activity, parameters).show(true) } false } /* * Start day of week */ val firstDayOfWeekPref = findPreference<SwitchPreferenceCompat>(getString(R.string.setting_category_start_day_of_week_key)) firstDayOfWeekPref?.isChecked = parameters.getCaldroidFirstDayOfWeek() == CaldroidFragment.SUNDAY firstDayOfWeekPref?.onPreferenceClickListener = Preference.OnPreferenceClickListener { parameters.setCaldroidFirstDayOfWeek(if ((firstDayOfWeekPref?.isChecked) == true) CaldroidFragment.SUNDAY else CaldroidFragment.MONDAY) true } /* * Backup */ findPreference<Preference>(getString(R.string.setting_category_backup))?.onPreferenceClickListener = Preference.OnPreferenceClickListener { startActivity(Intent(context, BackupSettingsActivity::class.java)) false } updateBackupPreferences() /* * Bind bug report button */ findPreference<Preference>(resources.getString(R.string.setting_category_bug_report_send_button_key))?.onPreferenceClickListener = Preference.OnPreferenceClickListener { val localId = parameters.getLocalId() val sendIntent = Intent() sendIntent.action = Intent.ACTION_SENDTO sendIntent.data = Uri.parse("mailto:") // only email apps should handle this sendIntent.putExtra(Intent.EXTRA_EMAIL, arrayOf(resources.getString(R.string.bug_report_email))) sendIntent.putExtra(Intent.EXTRA_TEXT, resources.getString(R.string.setting_category_bug_report_send_text, localId)) sendIntent.putExtra(Intent.EXTRA_SUBJECT, resources.getString(R.string.setting_category_bug_report_send_subject)) val packageManager = activity?.packageManager if (packageManager != null && sendIntent.resolveActivity(packageManager) != null) { startActivity(sendIntent) } else { Toast.makeText(activity, resources.getString(R.string.setting_category_bug_report_send_error), Toast.LENGTH_SHORT).show() } false } /* * Share app */ findPreference<Preference>(resources.getString(R.string.setting_category_share_app_key))?.onPreferenceClickListener = Preference.OnPreferenceClickListener { try { val sendIntent = Intent() sendIntent.action = Intent.ACTION_SEND sendIntent.putExtra(Intent.EXTRA_TEXT, resources.getString(R.string.app_invite_message) + "\n" + "https://play.google.com/store/apps/details?id=com.benoitletondor.easybudgetapp") sendIntent.type = "text/plain" startActivity(sendIntent) } catch (e: Exception) { Logger.error("An error occurred during sharing app activity start", e) } false } /* * App version */ val appVersionPreference = findPreference<Preference>(resources.getString(R.string.setting_category_app_version_key)) appVersionPreference?.title = resources.getString(R.string.setting_category_app_version_title, BuildConfig.VERSION_NAME) appVersionPreference?.onPreferenceClickListener = Preference.OnPreferenceClickListener { val i = Intent(Intent.ACTION_VIEW) i.data = Uri.parse("https://twitter.com/BenoitLetondor") activity?.startActivity(i) false } /* * Currency change button */ findPreference<Preference>(resources.getString(R.string.setting_category_currency_change_button_key))?.let { currencyPreference -> currencyPreference.onPreferenceClickListener = Preference.OnPreferenceClickListener { selectCurrencyDialog = SelectCurrencyFragment() selectCurrencyDialog!!.show((activity as SettingsActivity).supportFragmentManager, "SelectCurrency") false } setCurrencyPreferenceTitle(currencyPreference) } /* * Warning limit button */ findPreference<Preference>(resources.getString(R.string.setting_category_limit_set_button_key))?.let { limitWarningPreference -> limitWarningPreference.onPreferenceClickListener = Preference.OnPreferenceClickListener { val dialogView = activity?.layoutInflater?.inflate(R.layout.dialog_set_warning_limit, null) val limitEditText = dialogView?.findViewById<View>(R.id.warning_limit) as EditText limitEditText.setText(parameters.getLowMoneyWarningAmount().toString()) limitEditText.setSelection(limitEditText.text.length) // Put focus at the end of the text context?.let { context -> val builder = MaterialAlertDialogBuilder(context) builder.setTitle(R.string.adjust_limit_warning_title) builder.setMessage(R.string.adjust_limit_warning_message) builder.setView(dialogView) builder.setNegativeButton(R.string.cancel) { dialog, _ -> dialog.dismiss() } builder.setPositiveButton(R.string.ok) { _, _ -> var limitString = limitEditText.text.toString() if (limitString.trim { it <= ' ' }.isEmpty()) { limitString = "0" // Set a 0 value if no value is provided (will lead to an error displayed to the user) } try { val newLimit = Integer.valueOf(limitString) // Invalid value, alert the user if (newLimit <= 0) { throw IllegalArgumentException("limit should be > 0") } parameters.setLowMoneyWarningAmount(newLimit) setLimitWarningPreferenceTitle(limitWarningPreference) LocalBroadcastManager.getInstance(context).sendBroadcast(Intent(MainActivity.INTENT_LOW_MONEY_WARNING_THRESHOLD_CHANGED)) } catch (e: Exception) { MaterialAlertDialogBuilder(context) .setTitle(R.string.adjust_limit_warning_error_title) .setMessage(resources.getString(R.string.adjust_limit_warning_error_message)) .setPositiveButton(R.string.ok) { dialog1, _ -> dialog1.dismiss() } .show() } } val dialog = builder.show() // Directly show keyboard when the dialog pops limitEditText.onFocusChangeListener = View.OnFocusChangeListener { _, hasFocus -> // Check if the device doesn't have a physical keyboard if (hasFocus && resources.configuration.keyboard == Configuration.KEYBOARD_NOKEYS) { dialog.window?.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE) } } } false } setLimitWarningPreferenceTitle(limitWarningPreference) } /* * Premium status */ premiumCategory = findPreference(resources.getString(R.string.setting_category_premium_key))!! notPremiumCategory = findPreference(resources.getString(R.string.setting_category_not_premium_key))!! refreshPremiumPreference() /* * Show checked balance */ val showCheckedBalancePref = findPreference<CheckBoxPreference>(resources.getString(R.string.setting_category_show_checked_balance_key)) showCheckedBalancePref?.onPreferenceClickListener = Preference.OnPreferenceClickListener { parameters.setShouldShowCheckedBalance((it as CheckBoxPreference).isChecked) context?.let { context -> LocalBroadcastManager.getInstance(context).sendBroadcast(Intent(MainActivity.INTENT_SHOW_CHECKED_BALANCE_CHANGED)) } true } showCheckedBalancePref?.isChecked = parameters.getShouldShowCheckedBalance() /* * Notifications */ val updateNotifPref = findPreference<CheckBoxPreference>(resources.getString(R.string.setting_category_notifications_update_key)) updateNotifPref?.onPreferenceClickListener = Preference.OnPreferenceClickListener { val checked = (it as CheckBoxPreference).isChecked parameters.setUserAllowUpdatePushes(checked) if (checked) { showNotificationPermissionIfNeeded() } true } updateNotifPref?.isChecked = parameters.isUserAllowingUpdatePushes() /* * Hide dev preferences if needed */ val devCategory = findPreference<PreferenceCategory>(resources.getString(R.string.setting_category_dev_key)) if (!BuildConfig.DEV_PREFERENCES) { devCategory?.let { preferenceScreen.removePreference(it) } } else { /* * Show welcome screen button */ findPreference<Preference>(resources.getString(R.string.setting_category_show_welcome_screen_button_key))?.onPreferenceClickListener = Preference.OnPreferenceClickListener { context?.let { context -> LocalBroadcastManager.getInstance(context).sendBroadcast(Intent(MainActivity.INTENT_SHOW_WELCOME_SCREEN)) } activity?.finish() false } /* * Show premium screen */ findPreference<Preference>(resources.getString(R.string.setting_category_dev_show_premium_key))?.onPreferenceClickListener = Preference.OnPreferenceClickListener { showBecomePremiumDialog() false } } /* * Broadcast receiver */ val filter = IntentFilter(SelectCurrencyFragment.CURRENCY_SELECTED_INTENT) filter.addAction(INTENT_IAB_STATUS_CHANGED) filter.addAction(USER_GONE_PREMIUM_INTENT) receiver = object : BroadcastReceiver() { override fun onReceive(appContext: Context, intent: Intent) { if (SelectCurrencyFragment.CURRENCY_SELECTED_INTENT == intent.action && selectCurrencyDialog != null) { findPreference<Preference>(resources.getString(R.string.setting_category_currency_change_button_key))?.let { currencyPreference -> setCurrencyPreferenceTitle(currencyPreference) } selectCurrencyDialog!!.dismiss() selectCurrencyDialog = null } else if (INTENT_IAB_STATUS_CHANGED == intent.action) { try { refreshPremiumPreference() } catch (e: Exception) { Logger.error("Error while receiving INTENT_IAB_STATUS_CHANGED intent", e) } } else if (USER_GONE_PREMIUM_INTENT == intent.action) { context?.let { context -> MaterialAlertDialogBuilder(context) .setTitle(R.string.iab_purchase_success_title) .setMessage(R.string.iab_purchase_success_message) .setPositiveButton(R.string.ok) { dialog, _ -> dialog.dismiss() } .setOnDismissListener { showNotificationPermissionIfNeeded() } .show() } refreshPremiumPreference() } } } context?.let { context -> LocalBroadcastManager.getInstance(context).registerReceiver(receiver, filter) } /* * Check if we should show premium popup */ if (activity?.intent?.getBooleanExtra(SettingsActivity.SHOW_PREMIUM_INTENT_KEY, false) == true) { activity?.intent?.putExtra(SettingsActivity.SHOW_PREMIUM_INTENT_KEY, false) showBecomePremiumDialog() } /* * Check if we should show backup options */ if( activity?.intent?.getBooleanExtra(SHOW_BACKUP_INTENT_KEY, false) == true ) { activity?.intent?.putExtra(SHOW_BACKUP_INTENT_KEY, false) startActivity(Intent(context, BackupSettingsActivity::class.java)) } } private fun updateBackupPreferences() { findPreference<Preference>(getString(R.string.setting_category_backup))?.setSummary(if( parameters.isBackupEnabled() ) { R.string.backup_settings_backups_activated } else { R.string.backup_settings_backups_deactivated }) } private fun showNotificationPermissionIfNeeded() { if (Build.VERSION.SDK_INT < 33) { return } if (ContextCompat.checkSelfPermission(requireContext(), Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) { notificationRequestPermissionLauncher.launch(Manifest.permission.POST_NOTIFICATIONS) } } override fun onResume() { super.onResume() updateBackupPreferences() } /** * Set the currency preference title according to selected currency * * @param currencyPreference */ private fun setCurrencyPreferenceTitle(currencyPreference: Preference) { currencyPreference.title = resources.getString(R.string.setting_category_currency_change_button_title, parameters.getUserCurrency().symbol) } /** * Set the limit warning preference title according to the selected limit * * @param limitWarningPreferenceTitle */ private fun setLimitWarningPreferenceTitle(limitWarningPreferenceTitle: Preference) { limitWarningPreferenceTitle.title = resources.getString(R.string.setting_category_limit_set_button_title, CurrencyHelper.getFormattedCurrencyString(parameters, parameters.getLowMoneyWarningAmount().toDouble())) } /** * Show the right premium preference depending on the user state */ private fun refreshPremiumPreference() { val isPremium = iab.isUserPremium() if (isPremium) { if (notPremiumShown) { preferenceScreen.removePreference(notPremiumCategory) notPremiumShown = false } if (!premiumShown) { preferenceScreen.addPreference(premiumCategory) premiumShown = true } // Premium preference findPreference<Preference>(resources.getString(R.string.setting_category_premium_status_key))?.onPreferenceClickListener = Preference.OnPreferenceClickListener { context?.let {context -> MaterialAlertDialogBuilder(context) .setTitle(R.string.premium_popup_premium_title) .setMessage(R.string.premium_popup_premium_message) .setPositiveButton(R.string.ok) { dialog, _ -> dialog.dismiss() } .show() } false } // Daily reminder notif preference val dailyNotifPref = findPreference<CheckBoxPreference>(resources.getString(R.string.setting_category_notifications_daily_key)) dailyNotifPref?.onPreferenceClickListener = Preference.OnPreferenceClickListener { val checked = (it as CheckBoxPreference).isChecked parameters.setUserAllowDailyReminderPushes(checked) if (checked) { showNotificationPermissionIfNeeded() } true } dailyNotifPref?.isChecked = parameters.isUserAllowingDailyReminderPushes() // Monthly reminder for reports val monthlyNotifPref = findPreference<CheckBoxPreference>(resources.getString(R.string.setting_category_notifications_monthly_key)) monthlyNotifPref?.onPreferenceClickListener = Preference.OnPreferenceClickListener { val checked = (it as CheckBoxPreference).isChecked parameters.setUserAllowMonthlyReminderPushes(checked) if (checked) { showNotificationPermissionIfNeeded() } true } monthlyNotifPref?.isChecked = parameters.isUserAllowingMonthlyReminderPushes() // Theme findPreference<ListPreference>(getString(R.string.setting_category_app_theme_key))?.let { themePref -> val currentTheme = parameters.getTheme() themePref.value = currentTheme.value.toString() themePref.summary = themePref.entries[themePref.findIndexOfValue(themePref.value)] themePref.onPreferenceChangeListener = Preference.OnPreferenceChangeListener { _, newValue -> themePref.summary = themePref.entries[themePref.findIndexOfValue(newValue as String)] val newTheme = AppTheme.values().first { it.value == newValue.toInt() } parameters.setTheme(newTheme) AppCompatDelegate.setDefaultNightMode(newTheme.toPlatformValue()) true } } } else { if (premiumShown) { preferenceScreen.removePreference(premiumCategory) premiumShown = false } if (!notPremiumShown) { preferenceScreen.addPreference(notPremiumCategory) notPremiumShown = true } // Not premium preference findPreference<Preference>(resources.getString(R.string.setting_category_not_premium_status_key))?.onPreferenceClickListener = Preference.OnPreferenceClickListener { showBecomePremiumDialog() false } // Redeem promo code pref findPreference<Preference>(resources.getString(R.string.setting_category_premium_redeem_key))?.onPreferenceClickListener = Preference.OnPreferenceClickListener { activity?.let { activity -> val dialogView = activity.layoutInflater.inflate(R.layout.dialog_redeem_voucher, null) val voucherEditText = dialogView.findViewById<View>(R.id.voucher) as EditText val builder = MaterialAlertDialogBuilder(activity) .setTitle(R.string.voucher_redeem_dialog_title) .setMessage(R.string.voucher_redeem_dialog_message) .setView(dialogView) .setPositiveButton(R.string.voucher_redeem_dialog_cta) { dialog, _ -> dialog.dismiss() val promocode = voucherEditText.text.toString() if (promocode.trim { it <= ' ' }.isEmpty()) { MaterialAlertDialogBuilder(activity) .setTitle(R.string.voucher_redeem_error_dialog_title) .setMessage(R.string.voucher_redeem_error_code_invalid_dialog_message) .setPositiveButton(R.string.ok) { dialog12, _ -> dialog12.dismiss() } .show() } if (!launchRedeemPromocodeFlow(promocode)) { MaterialAlertDialogBuilder(activity) .setTitle(R.string.iab_purchase_error_title) .setMessage(resources.getString(R.string.iab_purchase_error_message, "Error redeeming promo code")) .setPositiveButton(R.string.ok) { dialog1, _ -> dialog1.dismiss() } .show() } } .setNegativeButton(R.string.cancel) { dialog, _ -> dialog.dismiss() } val dialog = builder.show() // Directly show keyboard when the dialog pops voucherEditText.onFocusChangeListener = View.OnFocusChangeListener { _, hasFocus -> // Check if the device doesn't have a physical keyboard if (hasFocus && resources.configuration.keyboard == Configuration.KEYBOARD_NOKEYS) { dialog.window?.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE) } } } false } } } private fun showBecomePremiumDialog() { activity?.let { activity -> val intent = Intent(activity, PremiumActivity::class.java) ActivityCompat.startActivityForResult(activity, intent, SettingsActivity.PREMIUM_ACTIVITY, null) } } /** * Launch the redeem promocode flow * * @param promocode the promocode to redeem */ private fun launchRedeemPromocodeFlow(promocode: String): Boolean { return try { val url = "https://play.google.com/redeem?code=" + URLEncoder.encode(promocode, "UTF-8") activity?.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(url))) true } catch (e: Exception) { Logger.error(false, "Error while redeeming promocode", e) false } } override fun onDestroy() { context?.let {context -> LocalBroadcastManager.getInstance(context).unregisterReceiver(receiver) } super.onDestroy() } }
apache-2.0
5c03ee2dade0716df0dfd8eb7abb2331
43.173633
218
0.618176
5.518377
false
false
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/box/delegatedProperty/local/localVarNoExplicitType.kt
4
387
package foo import kotlin.reflect.KProperty class Delegate { var inner = 1 operator fun getValue(t: Any?, p: KProperty<*>): Int = inner operator fun setValue(t: Any?, p: KProperty<*>, i: Int) { inner = i } } fun box(): String { var prop by Delegate() if (prop != 1) return "fail get" prop = 2 if (prop != 2) return "fail set" return "OK" }
apache-2.0
6c452c5767f10692e22b89fe92e43052
19.368421
64
0.583979
3.486486
false
false
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/box/sam/constructors/nonLiteralComparator.kt
2
295
// WITH_RUNTIME fun box(): String { val list = mutableListOf(3, 2, 4, 8, 1, 5) val expected = listOf(8, 5, 4, 3, 2, 1) val comparatorFun: (Int, Int) -> Int = { a, b -> b - a } list.sortWith(Comparator(comparatorFun)) return if (list == expected) "OK" else list.toString() }
apache-2.0
9cff68f5e94f14b9aeab3f43fedd0e22
31.777778
60
0.589831
3.010204
false
false
false
false
exponent/exponent
android/expoview/src/main/java/versioned/host/exp/exponent/modules/api/screens/SearchBarManager.kt
2
3296
package versioned.host.exp.exponent.modules.api.screens import com.facebook.react.bridge.JSApplicationIllegalArgumentException import com.facebook.react.common.MapBuilder import com.facebook.react.module.annotations.ReactModule import com.facebook.react.uimanager.ThemedReactContext import com.facebook.react.uimanager.ViewGroupManager import com.facebook.react.uimanager.annotations.ReactProp @ReactModule(name = SearchBarManager.REACT_CLASS) class SearchBarManager : ViewGroupManager<SearchBarView>() { override fun getName(): String { return REACT_CLASS } override fun createViewInstance(context: ThemedReactContext): SearchBarView { return SearchBarView(context) } override fun onAfterUpdateTransaction(view: SearchBarView) { super.onAfterUpdateTransaction(view) view.onUpdate() } @ReactProp(name = "autoCapitalize") fun setAutoCapitalize(view: SearchBarView, autoCapitalize: String?) { view.autoCapitalize = when (autoCapitalize) { null, "none" -> SearchBarView.SearchBarAutoCapitalize.NONE "words" -> SearchBarView.SearchBarAutoCapitalize.WORDS "sentences" -> SearchBarView.SearchBarAutoCapitalize.SENTENCES "characters" -> SearchBarView.SearchBarAutoCapitalize.CHARACTERS else -> throw JSApplicationIllegalArgumentException( "Forbidden auto capitalize value passed" ) } } @ReactProp(name = "autoFocus") fun setAutoFocus(view: SearchBarView, autoFocus: Boolean?) { view.autoFocus = autoFocus ?: false } @ReactProp(name = "barTintColor", customType = "Color") fun setTintColor(view: SearchBarView, color: Int?) { view.tintColor = color } @ReactProp(name = "disableBackButtonOverride") fun setDisableBackButtonOverride(view: SearchBarView, disableBackButtonOverride: Boolean?) { view.shouldOverrideBackButton = disableBackButtonOverride != true } @ReactProp(name = "inputType") fun setInputType(view: SearchBarView, inputType: String?) { view.inputType = when (inputType) { null, "text" -> SearchBarView.SearchBarInputTypes.TEXT "phone" -> SearchBarView.SearchBarInputTypes.PHONE "number" -> SearchBarView.SearchBarInputTypes.NUMBER "email" -> SearchBarView.SearchBarInputTypes.EMAIL else -> throw JSApplicationIllegalArgumentException( "Forbidden input type value" ) } } @ReactProp(name = "placeholder") fun setPlaceholder(view: SearchBarView, placeholder: String?) { view.placeholder = placeholder } @ReactProp(name = "textColor", customType = "Color") fun setTextColor(view: SearchBarView, color: Int?) { view.textColor = color } override fun getExportedCustomDirectEventTypeConstants(): Map<String, Any>? { return MapBuilder.builder<String, Any>() .put("onChangeText", MapBuilder.of("registrationName", "onChangeText")) .put("onSearchButtonPress", MapBuilder.of("registrationName", "onSearchButtonPress")) .put("onFocus", MapBuilder.of("registrationName", "onFocus")) .put("onBlur", MapBuilder.of("registrationName", "onBlur")) .put("onClose", MapBuilder.of("registrationName", "onClose")) .put("onOpen", MapBuilder.of("registrationName", "onOpen")) .build() } companion object { const val REACT_CLASS = "RNSSearchBar" } }
bsd-3-clause
0fd5f30713767f2195fcda6d90e3da3c
35.622222
94
0.734527
4.478261
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/j2k/services/src/org/jetbrains/kotlin/nj2k/inference/common/Solver.kt
6
8444
// 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.nj2k.inference.common import org.jetbrains.kotlin.utils.addToStdlib.safeAs internal class Solver( private val inferenceContext: InferenceContext, private val printConstraints: Boolean, private val defaultStateProvider: DefaultStateProvider ) { private val printer = DebugPrinter(inferenceContext) private fun List<Constraint>.printDebugInfo(step: Int) = with(printer) { if (printConstraints) { println("Step $step:") for (constraint in this@printDebugInfo) { println(constraint.asString()) } println() println("type variables:") for (typeVariable in inferenceContext.typeVariables) { if (typeVariable.state != State.UNUSED) { println("${typeVariable.name} := ${typeVariable.state}") } } println("---------------\n") } } fun solveConstraints(constraints: List<Constraint>) { val mutableConstraints = constraints.toMutableList() mutableConstraints.filterOutConstraintsWithUnusedState() var currentStep = ConstraintPriority.values().first() var i = 0 do { var somethingChanged = false with(mutableConstraints) { printDebugInfo(i) somethingChanged = handleConstraintsWithNullableLowerBound(currentStep) || somethingChanged somethingChanged = handleConstraintsWithNotNullUpperBound(currentStep) || somethingChanged somethingChanged = handleEqualsConstraints(currentStep) || somethingChanged somethingChanged = substituteConstraints() || somethingChanged cleanConstraints() } if (!somethingChanged) { if (currentStep.ordinal < ConstraintPriority.values().lastIndex) { currentStep = ConstraintPriority.values()[currentStep.ordinal + 1] somethingChanged = true } } if (!somethingChanged) { val typeVariable = mutableConstraints.getTypeVariableAsEqualsOrUpperBound() ?: inferenceContext.typeVariables.firstOrNull { !it.isFixed } if (typeVariable != null) { typeVariable.setStateIfNotFixed(defaultStateProvider.defaultStateFor(typeVariable)) somethingChanged = true } } i++ } while (somethingChanged) } private fun MutableList<Constraint>.cleanConstraints() { removeIf { constraint -> constraint is SubtypeConstraint && constraint.subtype is LiteralBound && constraint.supertype is LiteralBound } } private fun MutableList<Constraint>.handleConstraintsWithNullableLowerBound(step: ConstraintPriority): Boolean { var somethingChanged = false val nullableConstraints = getConstraintsWithNullableLowerBound(step) if (nullableConstraints.isNotEmpty()) { this -= nullableConstraints for ((_, upperBound) in nullableConstraints) { if (upperBound is TypeVariableBound) { somethingChanged = true upperBound.typeVariable.setStateIfNotFixed(State.UPPER) } } } return somethingChanged } private fun MutableList<Constraint>.handleConstraintsWithNotNullUpperBound(step: ConstraintPriority): Boolean { var somethingChanged = false val nullableConstraints = getConstraintsWithNotNullUpperBound(step) if (nullableConstraints.isNotEmpty()) { this -= nullableConstraints for ((lowerBound, _) in nullableConstraints) { if (lowerBound is TypeVariableBound) { somethingChanged = true lowerBound.typeVariable.setStateIfNotFixed(State.LOWER) } } } return somethingChanged } private fun ConstraintBound.fixedState(): State? = when { this is LiteralBound -> state this is TypeVariableBound && typeVariable.isFixed -> typeVariable.state else -> null } private fun MutableList<Constraint>.handleEqualsConstraints(step: ConstraintPriority): Boolean { var somethingChanged = false val equalsConstraints = filterIsInstance<EqualsConstraint>().filter { it.priority <= step } if (equalsConstraints.isNotEmpty()) { for (constraint in equalsConstraints) { val (leftBound, rightBound) = constraint when { leftBound is TypeVariableBound && rightBound.fixedState() != null -> { this -= constraint somethingChanged = true leftBound.typeVariable.setStateIfNotFixed(rightBound.fixedState()!!) } rightBound is TypeVariableBound && leftBound.fixedState() != null -> { this -= constraint somethingChanged = true rightBound.typeVariable.setStateIfNotFixed(leftBound.fixedState()!!) } } } } return somethingChanged } private fun List<Constraint>.substituteConstraints(): Boolean { var somethingChanged = false for (constraint in this) { if (constraint is SubtypeConstraint) { val (lower, upper) = constraint if (lower is TypeVariableBound && lower.typeVariable.isFixed) { somethingChanged = true constraint.subtype = lower.typeVariable.state.constraintBound() ?: continue } if (upper is TypeVariableBound && upper.typeVariable.isFixed) { somethingChanged = true constraint.supertype = upper.typeVariable.state.constraintBound() ?: continue } } } return somethingChanged } private fun List<Constraint>.getConstraintsWithNullableLowerBound(priority: ConstraintPriority) = filterIsInstance<SubtypeConstraint>().filter { constraint -> constraint.priority <= priority && constraint.subtype.safeAs<LiteralBound>()?.state == State.UPPER } private fun List<Constraint>.getConstraintsWithNotNullUpperBound(priority: ConstraintPriority) = filterIsInstance<SubtypeConstraint>().filter { constraint -> constraint.priority <= priority && constraint.supertype.safeAs<LiteralBound>()?.state == State.LOWER } private fun List<Constraint>.getTypeVariableAsEqualsOrUpperBound(): TypeVariable? { for (constraint in this) { when (constraint) { is SubtypeConstraint -> { constraint.supertype.safeAs<TypeVariableBound>() ?.typeVariable ?.takeIf { defaultStateProvider.defaultStateFor(it) == State.LOWER } ?.let { return it } constraint.subtype.safeAs<TypeVariableBound>() ?.typeVariable ?.takeIf { defaultStateProvider.defaultStateFor(it) == State.UPPER } ?.let { return it } } is EqualsConstraint -> { (constraint.left.safeAs<TypeVariableBound>() ?: constraint.right.safeAs<TypeVariableBound>()) ?.let { return it.typeVariable } } } } return null } private fun MutableList<Constraint>.filterOutConstraintsWithUnusedState() { removeIf { constraint -> when (constraint) { is SubtypeConstraint -> constraint.subtype.isUnused || constraint.supertype.isUnused is EqualsConstraint -> constraint.left.isUnused || constraint.right.isUnused } } } }
apache-2.0
d7a33ae58e981cd312e74ee424b5eeaf
40.596059
158
0.581833
6.07482
false
false
false
false
smmribeiro/intellij-community
plugins/groovy/src/org/jetbrains/plugins/groovy/util/moduleChooserUtil.kt
10
2527
// 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:JvmName("ModuleChooserUtil") package org.jetbrains.plugins.groovy.util import com.intellij.ide.util.PropertiesComponent import com.intellij.openapi.module.Module import com.intellij.openapi.module.ModuleType import com.intellij.openapi.project.Project import com.intellij.openapi.projectRoots.JavaSdkType import com.intellij.openapi.roots.ModuleRootManager import com.intellij.openapi.roots.ui.configuration.ModulesAlphaComparator import com.intellij.openapi.ui.popup.ListPopup import com.intellij.openapi.ui.popup.ListPopupStep import com.intellij.ui.popup.list.ListPopupImpl import com.intellij.util.Consumer import com.intellij.util.Function import org.jetbrains.plugins.groovy.config.GroovyFacetUtil private const val GROOVY_LAST_MODULE = "Groovy.Last.Module.Chosen" fun selectModule(project: Project, modules: List<Module>, version: Function<Module, String>, consumer: Consumer<Module>) { modules.singleOrNull()?.let { consumer.consume(it) return } createSelectModulePopup(project, modules, version::`fun`, consumer::consume).showCenteredInCurrentWindow(project) } fun createSelectModulePopup(project: Project, modules: List<Module>, version: (Module) -> String, consumer: (Module) -> Unit): ListPopup { val step = createSelectModulePopupStep(project, modules.sortedWith(ModulesAlphaComparator.INSTANCE), consumer) return object : ListPopupImpl(project, step) { override fun getListElementRenderer() = RightTextCellRenderer(super.getListElementRenderer(), version) } } private fun createSelectModulePopupStep(project: Project, modules: List<Module>, consumer: (Module) -> Unit): ListPopupStep<Module> { val propertiesComponent = PropertiesComponent.getInstance(project) val step = GroovySelectModuleStep(modules) { propertiesComponent.setValue(GROOVY_LAST_MODULE, it.name) consumer(it) } propertiesComponent.getValue(GROOVY_LAST_MODULE)?.let { lastModuleName -> step.defaultOptionIndex = modules.indexOfFirst { it.name == lastModuleName } } return step } fun hasJavaSdk(module: Module): Boolean = ModuleRootManager.getInstance(module).sdk?.sdkType is JavaSdkType fun hasAcceptableModuleType(module: Module): Boolean = GroovyFacetUtil.isAcceptableModuleType(ModuleType.get(module))
apache-2.0
01a52cadd7c45294a07ab2e0ebc0e05d
41.116667
140
0.757816
4.425569
false
false
false
false
android/compose-samples
Jetcaster/app/src/main/java/com/example/jetcaster/data/CategoryStore.kt
1
2901
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.jetcaster.data import com.example.jetcaster.data.room.CategoriesDao import com.example.jetcaster.data.room.EpisodesDao import com.example.jetcaster.data.room.PodcastCategoryEntryDao import com.example.jetcaster.data.room.PodcastsDao import kotlinx.coroutines.flow.Flow /** * A data repository for [Category] instances. */ class CategoryStore( private val categoriesDao: CategoriesDao, private val categoryEntryDao: PodcastCategoryEntryDao, private val episodesDao: EpisodesDao, private val podcastsDao: PodcastsDao ) { /** * Returns a flow containing a list of categories which is sorted by the number * of podcasts in each category. */ fun categoriesSortedByPodcastCount( limit: Int = Integer.MAX_VALUE ): Flow<List<Category>> { return categoriesDao.categoriesSortedByPodcastCount(limit) } /** * Returns a flow containing a list of podcasts in the category with the given [categoryId], * sorted by the their last episode date. */ fun podcastsInCategorySortedByPodcastCount( categoryId: Long, limit: Int = Int.MAX_VALUE ): Flow<List<PodcastWithExtraInfo>> { return podcastsDao.podcastsInCategorySortedByLastEpisode(categoryId, limit) } /** * Returns a flow containing a list of episodes from podcasts in the category with the * given [categoryId], sorted by the their last episode date. */ fun episodesFromPodcastsInCategory( categoryId: Long, limit: Int = Integer.MAX_VALUE ): Flow<List<EpisodeToPodcast>> { return episodesDao.episodesFromPodcastsInCategory(categoryId, limit) } /** * Adds the category to the database if it doesn't already exist. * * @return the id of the newly inserted/existing category */ suspend fun addCategory(category: Category): Long { return when (val local = categoriesDao.getCategoryWithName(category.name)) { null -> categoriesDao.insert(category) else -> local.id } } suspend fun addPodcastToCategory(podcastUri: String, categoryId: Long) { categoryEntryDao.insert( PodcastCategoryEntry(podcastUri = podcastUri, categoryId = categoryId) ) } }
apache-2.0
7f809adaeed77bff9c209219335cffc6
33.951807
96
0.706653
4.429008
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/live-templates/tests/testData/iter.exp.kt
13
492
import java.io.InputStream import java.util.ArrayList import java.io.FileInputStream import java.util.HashSet class MyClass { public var collection : HashSet<Int>? = null private var isAlive : Boolean = false fun main(args : Array<String>, v : Int, o: Any) { var str = "" val myList = ArrayList<String>() val stream = FileInputStream(".") if (o is String) { for (arg in args) { <caret> } } } }
apache-2.0
6db6e84d03ab5e9b6fddbc4a09b27829
23.6
53
0.569106
4.169492
false
false
false
false
google/intellij-community
plugins/kotlin/completion/impl-k2/src/org/jetbrains/kotlin/idea/completion/impl/k2/contributors/keywords/OverrideKeywordHandler.kt
2
7699
// 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.completion.contributors.keywords import com.intellij.codeInsight.completion.CompletionParameters import com.intellij.codeInsight.lookup.LookupElement import com.intellij.icons.AllIcons import com.intellij.openapi.project.Project import com.intellij.ui.RowIcon import org.jetbrains.kotlin.analysis.api.KtAllowAnalysisOnEdt import org.jetbrains.kotlin.descriptors.Modality import org.jetbrains.kotlin.idea.completion.* import org.jetbrains.kotlin.idea.completion.context.FirBasicCompletionContext import org.jetbrains.kotlin.idea.completion.keywords.CompletionKeywordHandler import org.jetbrains.kotlin.idea.core.overrideImplement.* import org.jetbrains.kotlin.idea.core.overrideImplement.KtClassMember import org.jetbrains.kotlin.idea.core.overrideImplement.KtGenerateMembersHandler import org.jetbrains.kotlin.idea.core.overrideImplement.KtOverrideMembersHandler import org.jetbrains.kotlin.idea.core.overrideImplement.generateMember import org.jetbrains.kotlin.analysis.api.KtAnalysisSession import org.jetbrains.kotlin.analysis.api.analyze import org.jetbrains.kotlin.analysis.api.lifetime.allowAnalysisOnEdt import org.jetbrains.kotlin.analysis.api.symbols.KtCallableSymbol import org.jetbrains.kotlin.analysis.api.symbols.KtFunctionSymbol import org.jetbrains.kotlin.analysis.api.symbols.markers.KtSymbolWithModality import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType import org.jetbrains.kotlin.idea.KtIconProvider.getIcon import org.jetbrains.kotlin.analysis.api.symbols.markers.KtNamedSymbol import org.jetbrains.kotlin.analysis.api.symbols.nameOrAnonymous import org.jetbrains.kotlin.analysis.api.symbols.pointers.KtSymbolPointer import org.jetbrains.kotlin.idea.util.application.runWriteAction internal class OverrideKeywordHandler( private val basicContext: FirBasicCompletionContext ) : CompletionKeywordHandler<KtAnalysisSession>(KtTokens.OVERRIDE_KEYWORD) { @OptIn(ExperimentalStdlibApi::class) override fun KtAnalysisSession.createLookups( parameters: CompletionParameters, expression: KtExpression?, lookup: LookupElement, project: Project ): Collection<LookupElement> { val result = mutableListOf(lookup) val position = parameters.position val isConstructorParameter = position.getNonStrictParentOfType<KtPrimaryConstructor>() != null val classOrObject = position.getNonStrictParentOfType<KtClassOrObject>() ?: return result val members = collectMembers(classOrObject, isConstructorParameter) for (member in members) { result += createLookupElementToGenerateSingleOverrideMember(member, classOrObject, isConstructorParameter, project) } return result } private fun KtAnalysisSession.collectMembers(classOrObject: KtClassOrObject, isConstructorParameter: Boolean): List<KtClassMember> { val allMembers = KtOverrideMembersHandler().collectMembersToGenerate(classOrObject) return if (isConstructorParameter) { allMembers.mapNotNull { member -> if (member.memberInfo.isProperty) { member.copy(bodyType = BodyType.FromTemplate, preferConstructorParameter = true) } else null } } else allMembers.toList() } @OptIn(KtAllowAnalysisOnEdt::class) private fun KtAnalysisSession.createLookupElementToGenerateSingleOverrideMember( member: KtClassMember, classOrObject: KtClassOrObject, isConstructorParameter: Boolean, project: Project ): OverridesCompletionLookupElementDecorator { val memberSymbol = member.symbol check(memberSymbol is KtNamedSymbol) val text = getSymbolTextForLookupElement(memberSymbol) val baseIcon = getIcon(memberSymbol) val isImplement = (memberSymbol as? KtSymbolWithModality)?.modality == Modality.ABSTRACT val additionalIcon = if (isImplement) AllIcons.Gutter.ImplementingMethod else AllIcons.Gutter.OverridingMethod val icon = RowIcon(baseIcon, additionalIcon) val baseClass = classOrObject.getClassOrObjectSymbol() val baseClassIcon = getIcon(baseClass) val isSuspendFunction = (memberSymbol as? KtFunctionSymbol)?.isSuspend == true val baseClassName = baseClass.nameOrAnonymous.asString() val memberPointer = memberSymbol.createPointer() val baseLookupElement = with(basicContext.lookupElementFactory) { createLookupElement(memberSymbol, basicContext.importStrategyDetector) } ?: error("Lookup element should be available for override completion") return OverridesCompletionLookupElementDecorator( baseLookupElement, declaration = null, text, isImplement, icon, baseClassName, baseClassIcon, isConstructorParameter, isSuspendFunction, generateMember = { generateMemberInNewAnalysisSession(classOrObject, memberPointer, member, project) }, shortenReferences = { element -> val shortenings = allowAnalysisOnEdt { analyze(classOrObject) { collectPossibleReferenceShortenings(element.containingKtFile, element.textRange) } } runWriteAction { shortenings.invokeShortening() } } ) } private fun KtAnalysisSession.getSymbolTextForLookupElement(memberSymbol: KtCallableSymbol): String = buildString { append(KtTokens.OVERRIDE_KEYWORD.value) .append(" ") .append(memberSymbol.render(renderingOptionsForLookupElementRendering)) if (memberSymbol is KtFunctionSymbol) { append(" {...}") } } @OptIn(KtAllowAnalysisOnEdt::class) private fun generateMemberInNewAnalysisSession( classOrObject: KtClassOrObject, memberPointer: KtSymbolPointer<KtCallableSymbol>, member: KtClassMember, project: Project ) = allowAnalysisOnEdt { analyze(classOrObject) { val memberInCorrectAnalysisSession = createCopyInCurrentAnalysisSession(memberPointer, member) generateMember( project, memberInCorrectAnalysisSession, classOrObject, copyDoc = false, mode = MemberGenerateMode.OVERRIDE ) } } //todo temporary hack until KtSymbolPointer is properly implemented private fun KtAnalysisSession.createCopyInCurrentAnalysisSession( memberPointer: KtSymbolPointer<KtCallableSymbol>, member: KtClassMember ) = KtClassMember( KtClassMemberInfo( memberPointer.restoreSymbol() ?: error("Cannot restore symbol from $memberPointer"), member.memberInfo.memberText, member.memberInfo.memberIcon, member.memberInfo.containingSymbolText, member.memberInfo.containingSymbolIcon, ), member.bodyType, member.preferConstructorParameter, ) companion object { private val renderingOptionsForLookupElementRendering = KtGenerateMembersHandler.renderOption.copy( renderUnitReturnType = false, renderDeclarationHeader = true ) } }
apache-2.0
ed31273c4f3505f81d74cc27594dac0c
44.02924
158
0.716457
5.603348
false
false
false
false
fabmax/kool
kool-physics/src/jsMain/kotlin/de/fabmax/kool/physics/articulations/Articulation.kt
1
1044
package de.fabmax.kool.physics.articulations import de.fabmax.kool.math.Mat4f import de.fabmax.kool.physics.MemoryStack import de.fabmax.kool.physics.Physics import de.fabmax.kool.physics.toPxTransform import physx.PxArticulation actual class Articulation : CommonArticulation() { val pxArticulation: PxArticulation init { Physics.checkIsLoaded() pxArticulation = Physics.physics.createArticulation() } actual fun createLink(parent: ArticulationLink?, pose: Mat4f): ArticulationLink { return MemoryStack.stackPush().use { mem -> val pxPose = pose.toPxTransform(mem.createPxTransform()) val pxLink = pxArticulation.createLink(parent?.pxLink, pxPose) val link = ArticulationLink(pxLink, parent) mutLinks += link link } } actual fun wakeUp() { pxArticulation.wakeUp() } actual fun putToSleep() { pxArticulation.putToSleep() } override fun release() { pxArticulation.release() } }
apache-2.0
a3c5ee66734eb68906dfdf8eb8a6bc40
25.794872
85
0.672414
4.368201
false
false
false
false
evernote/android-state
library/src/test/kotlin/com/evernote/android/state/test/TestKotlinPrivateInnerClass.kt
1
2454
package com.evernote.android.state.test import android.os.Parcel import android.os.Parcelable import com.evernote.android.state.StateReflection /** * @author rwondratschek */ class TestKotlinPrivateInnerClass { @StateReflection private var inner= Inner.A @StateReflection private var parcelable = ParcelableImpl(1) @StateReflection private var innerList = arrayListOf(Inner.A) @StateReflection private var parcelableList = arrayListOf(ParcelableImpl(1)) init { setToA() } fun setToA() { inner = Inner.A parcelable = ParcelableImpl(1) innerList = arrayListOf(Inner.A) parcelableList = arrayListOf(ParcelableImpl(1)) } fun setToB() { inner = Inner.B parcelable = ParcelableImpl(2) innerList = arrayListOf(Inner.B) parcelableList = arrayListOf(ParcelableImpl(2)) } fun isA(): Boolean { return inner == Inner.A && parcelable.value == 1 && innerList[0] == Inner.A && parcelableList[0].value == 1 } fun isB(): Boolean { return inner == Inner.B && parcelable.value == 2 && innerList[0] == Inner.B && parcelableList[0].value == 2 } private enum class Inner { A, B } private class ParcelableImpl : Parcelable { var value: Int = 0 constructor(anInt: Int) { value = anInt } protected constructor(`in`: Parcel) { value = `in`.readInt() } override fun equals(o: Any?): Boolean { if (this === o) return true if (o == null || javaClass != o.javaClass) return false val that = o as ParcelableImpl? return value == that!!.value } override fun hashCode(): Int { return value } override fun writeToParcel(dest: Parcel, flags: Int) { dest.writeInt(value) } override fun describeContents(): Int { return 0 } companion object { val CREATOR: Parcelable.Creator<ParcelableImpl> = object : Parcelable.Creator<ParcelableImpl> { override fun createFromParcel(`in`: Parcel): ParcelableImpl { return ParcelableImpl(`in`) } override fun newArray(size: Int): Array<ParcelableImpl?> { return arrayOfNulls(size) } } } } }
epl-1.0
4ee7e382c3c05931938eecd9cccba68a
23.79798
115
0.57172
4.612782
false
false
false
false
vanniktech/lint-rules
lint-rules-android-lint/src/test/java/com/vanniktech/lintrules/android/Stubs.kt
1
1084
@file:Suppress("UnstableApiUsage") // We know that Lint APIs aren't final. package com.vanniktech.lintrules.android import com.android.tools.lint.checks.infrastructure.TestFiles val stubJUnitTest = TestFiles.java( """ package org.junit; public @interface Test { } """, ).indented() val stubJUnitIgnore = TestFiles.java( """ package org.junit; public @interface Test { } """, ).indented() val stubAnnotationTest = TestFiles.java( """ package my.custom; public @interface Test { } """, ).indented() val stubAnnotationSomething = TestFiles.java( """ package my.custom; public @interface Something { } """, ).indented() fun viewBindingProject() = TestFiles.gradle( """ apply plugin: 'com.android.library' android { buildFeatures { viewBinding = true } } """, ) .indented() fun resourcePrefix(prefix: String) = TestFiles.gradle( """ apply plugin: 'com.android.library' android { resourcePrefix '$prefix' } """, ) .indented()
apache-2.0
6974fcfe12c8438529451abfd863b8c1
16.770492
74
0.614391
4.090566
false
true
false
false
MyPureCloud/platform-client-sdk-common
resources/sdk/purecloudkotlin/extensions/connector/okhttp/OkHttpClientConnector.kt
1
3558
package com.mypurecloud.sdk.v2.connector.okhttp import com.google.common.util.concurrent.SettableFuture import com.mypurecloud.sdk.v2.AsyncApiCallback import com.mypurecloud.sdk.v2.connector.ApiClientConnector import com.mypurecloud.sdk.v2.connector.ApiClientConnectorRequest import com.mypurecloud.sdk.v2.connector.ApiClientConnectorResponse import com.squareup.okhttp.* import java.io.IOException import java.util.concurrent.Future class OkHttpClientConnector(private val client: OkHttpClient) : ApiClientConnector { @Throws(IOException::class) override fun invoke(request: ApiClientConnectorRequest): ApiClientConnectorResponse { val call = client.newCall(buildRequest(request)) return OkHttpResponse(call.execute()) } override fun invokeAsync(request: ApiClientConnectorRequest, callback: AsyncApiCallback<ApiClientConnectorResponse?>): Future<ApiClientConnectorResponse> { val future = SettableFuture.create<ApiClientConnectorResponse>() try { val call = client.newCall(buildRequest(request)) call.enqueue(object : Callback { override fun onFailure(request: Request, e: IOException) { callback.onFailed(e) future.setException(e) } @Throws(IOException::class) override fun onResponse(response: Response) { val okHttpResponse = OkHttpResponse(response) callback.onCompleted(okHttpResponse) future.set(OkHttpResponse(response)) } }) } catch (exception: Throwable) { callback.onFailed(exception) future.setException(exception) } return future } @Throws(IOException::class) private fun buildRequest(request: ApiClientConnectorRequest): Request { var builder = Request.Builder() .url(request.url) val headers = request.headers if (headers.isNotEmpty()) { for ((key, value) in headers) { builder = builder.addHeader(key, value) } } val method = request.method builder = when (method) { "GET" -> { builder.get() } "HEAD" -> { builder.head() } "POST" -> { builder.post(createBody(request)) } "PUT" -> { builder.put(createBody(request)) } "DELETE" -> { builder.delete() } "PATCH" -> { builder.patch(createBody(request)) } else -> { throw IllegalStateException("Unknown method type $method") } } return builder.build() } @Throws(IOException::class) private fun createBody(request: ApiClientConnectorRequest): RequestBody { var contentType = "application/json" val headers = request.headers if (headers.isNotEmpty()) { for (name in headers.keys) { if (name.equals("content-type", ignoreCase = true)) { contentType = headers[name] ?: "" break } } } return if (request.hasBody()) { RequestBody.create(MediaType.parse(contentType), request.readBody()) } else RequestBody.create(null, ByteArray(0)) } @Throws(Exception::class) override fun close() { } }
mit
1d4211c13cb1943af2ed32b19bb7f762
34.58
159
0.580101
5.03966
false
false
false
false
siosio/intellij-community
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/typing/util.kt
1
2207
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. @file:JvmName("TypeUtils") package org.jetbrains.plugins.groovy.lang.typing import com.intellij.lang.java.beans.PropertyKind import com.intellij.psi.* import org.jetbrains.plugins.groovy.lang.psi.api.GroovyResolveResult import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.TypesUtil import org.jetbrains.plugins.groovy.lang.psi.util.checkKind import org.jetbrains.plugins.groovy.lang.resolve.api.GroovyProperty /** * @return boxed type if [this] is a primitive type, otherwise [this] type */ fun PsiType.box(context: PsiElement): PsiType { if (this !is PsiPrimitiveType || this == PsiType.NULL) return this val typeName = boxedTypeName ?: error("This type is not NULL and still doesn't have boxed type name") return TypesUtil.createType(typeName, context) } fun getReadPropertyType(result: GroovyResolveResult): PsiType? { val baseType = getReadPropertyBaseType(result) ?: return null return result.substitutor.substitute(baseType) } private fun getReadPropertyBaseType(result: GroovyResolveResult): PsiType? { val resolved = result.element ?: return null if (resolved is GroovyProperty) { return resolved.propertyType } else if (resolved is PsiVariable) { return resolved.type } else if (resolved is PsiMethod) { if (resolved.checkKind(PropertyKind.GETTER) || resolved.checkKind(PropertyKind.BOOLEAN_GETTER)) { return resolved.returnType } } return null } fun getWritePropertyType(result: GroovyResolveResult): PsiType? { val baseType = getWritePropertyBaseType(result) ?: return null return result.substitutor.substitute(baseType) } private fun getWritePropertyBaseType(result: GroovyResolveResult): PsiType? { val resolved = result.element ?: return null if (resolved is GroovyProperty) { return resolved.propertyType } else if (resolved is PsiVariable) { return resolved.type } else if (resolved is PsiMethod && resolved.checkKind(PropertyKind.SETTER)) { return resolved.parameterList.parameters[0].type } else { return null } }
apache-2.0
106e6bbb4d126d781c6e1cf0f3d1f515
34.596774
158
0.76348
4.187856
false
false
false
false
jwren/intellij-community
plugins/kotlin/fir-fe10-binding/src/org/jetbrains/kotlin/idea/fir/fe10/BaseDescriptorsWrappers.kt
1
37079
// 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.fir.fe10 import org.jetbrains.kotlin.analysis.api.KtConstantInitializerValue import org.jetbrains.kotlin.analysis.api.annotations.* import org.jetbrains.kotlin.analysis.api.base.KtConstantValue import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.descriptors.annotations.AnnotationDescriptor import org.jetbrains.kotlin.descriptors.annotations.Annotations import org.jetbrains.kotlin.descriptors.impl.AbstractReceiverParameterDescriptor import org.jetbrains.kotlin.descriptors.impl.ReceiverParameterDescriptorImpl import org.jetbrains.kotlin.analysis.api.symbols.* import org.jetbrains.kotlin.analysis.api.symbols.markers.* import org.jetbrains.kotlin.analysis.api.types.KtType import org.jetbrains.kotlin.ir.util.IdSignature import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.name.SpecialNames import org.jetbrains.kotlin.psi.KtPureElement import org.jetbrains.kotlin.resolve.constants.* import org.jetbrains.kotlin.resolve.scopes.MemberScope import org.jetbrains.kotlin.resolve.scopes.receivers.ExtensionReceiver import org.jetbrains.kotlin.resolve.scopes.receivers.ImplicitClassReceiver import org.jetbrains.kotlin.resolve.scopes.receivers.ReceiverValue import org.jetbrains.kotlin.resolve.source.toSourceElement import org.jetbrains.kotlin.storage.StorageManager import org.jetbrains.kotlin.types.* import org.jetbrains.kotlin.utils.addToStdlib.safeAs /** * List of known problems/not-implemented: * - getOrigin return itself all the time. Formally it should return "unsubstituted" version of itself, but it isn't clear, * if we really needed that nor how to implemented it. Btw, it is relevant only to member functions/properties (unlikely, but may be to * inner classes) and not for "resulting descriptor". I.e. only class/interface type parameters could be substituted in FIR, * there is no "resulting descriptor" and type arguments are passed together with the target function. * - equals on descriptors and type constructors. It isn't clear what type of equality we should implement, * will figure that later o real cases. * See the functions below */ internal fun FE10BindingContext.containerDeclarationImplementationPostponed(): Nothing = implementationPostponed("It isn't clear what we really need and how to implement it") internal fun FE10BindingContext.typeAliasImplementationPlanned(): Nothing = implementationPlanned("It is easy to implement, but it isn't first priority") interface KtSymbolBasedNamed : Named { val ktSymbol: KtNamedSymbol override fun getName(): Name = ktSymbol.name } private fun Visibility.toDescriptorVisibility(): DescriptorVisibility = when (this) { Visibilities.Public -> DescriptorVisibilities.PUBLIC Visibilities.Private -> DescriptorVisibilities.PRIVATE Visibilities.PrivateToThis -> DescriptorVisibilities.PRIVATE_TO_THIS Visibilities.Protected -> DescriptorVisibilities.PROTECTED Visibilities.Internal -> DescriptorVisibilities.INTERNAL Visibilities.Local -> DescriptorVisibilities.LOCAL else -> error("Unknown visibility: $this") } private fun KtClassKind.toDescriptorKlassKind(): ClassKind = when (this) { KtClassKind.CLASS -> ClassKind.CLASS KtClassKind.ENUM_CLASS -> ClassKind.ENUM_CLASS KtClassKind.ENUM_ENTRY -> ClassKind.ENUM_ENTRY KtClassKind.ANNOTATION_CLASS -> ClassKind.ANNOTATION_CLASS KtClassKind.OBJECT, KtClassKind.COMPANION_OBJECT, KtClassKind.ANONYMOUS_OBJECT -> ClassKind.OBJECT KtClassKind.INTERFACE -> ClassKind.INTERFACE } private fun KtAnnotationValue.toConstantValue(): ConstantValue<*> { return when (this) { KtUnsupportedAnnotationValue -> ErrorValue.create("Unsupported annotation value") is KtArrayAnnotationValue -> ArrayValue(values.map { it.toConstantValue() }) { TODO() } is KtAnnotationApplicationValue -> TODO() is KtKClassAnnotationValue.KtNonLocalKClassAnnotationValue -> KClassValue(classId, arrayDimensions = 0) is KtKClassAnnotationValue.KtLocalKClassAnnotationValue -> TODO() is KtKClassAnnotationValue.KtErrorClassAnnotationValue -> ErrorValue.create("Unresolved class") is KtEnumEntryAnnotationValue -> { val callableId = callableId ?: return ErrorValue.create("Unresolved enum entry") val classId = callableId.classId ?: return ErrorValue.create("Unresolved enum entry") EnumValue(classId, callableId.callableName) } is KtConstantAnnotationValue -> constantValue.toConstantValue() } } private fun KtConstantValue.toConstantValue(): ConstantValue<*> = when (this) { is KtConstantValue.KtErrorConstantValue -> ErrorValue.create(errorMessage) else -> when (constantValueKind) { ConstantValueKind.Null -> NullValue() ConstantValueKind.Boolean -> BooleanValue(value as Boolean) ConstantValueKind.Char -> CharValue(value as Char) ConstantValueKind.Byte -> ByteValue(value as Byte) ConstantValueKind.Short -> ShortValue(value as Short) ConstantValueKind.Int -> IntValue(value as Int) ConstantValueKind.Long -> LongValue(value as Long) ConstantValueKind.String -> StringValue(value as String) ConstantValueKind.Float -> FloatValue(value as Float) ConstantValueKind.Double -> DoubleValue(value as Double) ConstantValueKind.UnsignedByte -> UByteValue(value as Byte) ConstantValueKind.UnsignedShort -> UShortValue(value as Short) ConstantValueKind.UnsignedInt -> UIntValue(value as Int) ConstantValueKind.UnsignedLong -> ULongValue(value as Long) else -> error("Unexpected constant KtSimpleConstantValue: $value (class: ${value?.javaClass}") } } abstract class KtSymbolBasedDeclarationDescriptor(val context: FE10BindingContext) : DeclarationDescriptorWithSource { abstract val ktSymbol: KtSymbol override val annotations: Annotations get() { val ktAnnotations = (ktSymbol as? KtAnnotatedSymbol)?.annotations ?: return Annotations.EMPTY return Annotations.create(ktAnnotations.map { KtSymbolBasedAnnotationDescriptor(it, context) }) } override fun getSource(): SourceElement = ktSymbol.psi.safeAs<KtPureElement>().toSourceElement() override fun getContainingDeclaration(): DeclarationDescriptor { if (ktSymbol !is KtSymbolWithKind) error("ContainingDeclaration should be overridden") val containerSymbol = context.withAnalysisSession { (ktSymbol as KtSymbolWithKind).getContainingSymbol() } if (containerSymbol != null) return containerSymbol.toDeclarationDescriptor(context) // i.e. declaration is top-level return KtSymbolBasedPackageFragmentDescriptor(getPackageFqNameIfTopLevel(), context) } protected abstract fun getPackageFqNameIfTopLevel(): FqName private fun KtSymbol.toSignature(): IdSignature = context.ktAnalysisSessionFacade.toSignature(this) override fun equals(other: Any?): Boolean { if (other === this) return true if (other !is KtSymbolBasedDeclarationDescriptor) return false ktSymbol.psi?.let { return other.ktSymbol.psi == it } return ktSymbol.toSignature() == other.ktSymbol.toSignature() } override fun hashCode(): Int { ktSymbol.psi?.let { return it.hashCode() } return ktSymbol.toSignature().hashCode() } override fun <R : Any?, D : Any?> accept(visitor: DeclarationDescriptorVisitor<R, D>?, data: D): R = noImplementation() override fun acceptVoid(visitor: DeclarationDescriptorVisitor<Void, Void>?): Unit = noImplementation() // stub for automatic Substitutable<T> implementation for all relevant subclasses fun substitute(substitutor: TypeSubstitutor): Nothing = noImplementation() protected fun noImplementation(): Nothing = context.noImplementation("ktSymbol = $ktSymbol") protected fun implementationPostponed(): Nothing = context.implementationPostponed("ktSymbol = $ktSymbol") protected fun implementationPlanned(): Nothing = context.implementationPlanned("ktSymbol = $ktSymbol") } class KtSymbolBasedAnnotationDescriptor( private val ktAnnotationCall: KtAnnotationApplication, val context: FE10BindingContext ) : AnnotationDescriptor { override val type: KotlinType get() = context.implementationPlanned("ktAnnotationCall = $ktAnnotationCall") override val fqName: FqName? get() = ktAnnotationCall.classId?.asSingleFqName() override val allValueArguments: Map<Name, ConstantValue<*>> = ktAnnotationCall.arguments.associate { it.name to it.expression.toConstantValue() } override val source: SourceElement get() = ktAnnotationCall.psi.toSourceElement() } class KtSymbolBasedClassDescriptor(override val ktSymbol: KtNamedClassOrObjectSymbol, context: FE10BindingContext) : KtSymbolBasedDeclarationDescriptor(context), KtSymbolBasedNamed, ClassDescriptor { override fun isInner(): Boolean = ktSymbol.isInner override fun isCompanionObject(): Boolean = ktSymbol.classKind == KtClassKind.COMPANION_OBJECT override fun isData(): Boolean = ktSymbol.isData override fun isInline(): Boolean = ktSymbol.isInline // seems like th`is `flag should be removed in favor of isValue override fun isValue(): Boolean = ktSymbol.isInline override fun isFun(): Boolean = ktSymbol.isFun override fun isExpect(): Boolean = implementationPostponed() override fun isActual(): Boolean = implementationPostponed() override fun isExternal(): Boolean = ktSymbol.isExternal override fun getVisibility(): DescriptorVisibility = ktSymbol.visibility.toDescriptorVisibility() override fun getModality(): Modality = ktSymbol.modality override fun getKind(): ClassKind = ktSymbol.classKind.toDescriptorKlassKind() override fun getCompanionObjectDescriptor(): ClassDescriptor? = ktSymbol.companionObject?.let { KtSymbolBasedClassDescriptor(it, context) } override fun getTypeConstructor(): TypeConstructor = KtSymbolBasedClassTypeConstructor(this) override fun getDeclaredTypeParameters(): List<TypeParameterDescriptor> = getTypeParameters(ktSymbol) override fun getDefaultType(): SimpleType { val arguments = TypeUtils.getDefaultTypeProjections(typeConstructor.parameters) return KotlinTypeFactory.simpleTypeWithNonTrivialMemberScope( TypeAttributes.Empty, typeConstructor, arguments, false, MemberScopeForKtSymbolBasedDescriptors { "ktSymbol = $ktSymbol" } ) } override fun getThisAsReceiverParameter(): ReceiverParameterDescriptor = ReceiverParameterDescriptorImpl(this, ImplicitClassReceiver(this), Annotations.EMPTY) override fun getContextReceivers(): List<ReceiverParameterDescriptor> = implementationPlanned() override fun getOriginal(): ClassDescriptor = this override fun getUnsubstitutedPrimaryConstructor(): ClassConstructorDescriptor? = context.withAnalysisSession { ktSymbol.getDeclaredMemberScope().getConstructors().firstOrNull { it.isPrimary } ?.let { KtSymbolBasedConstructorDescriptor(it, this@KtSymbolBasedClassDescriptor) } } @OptIn(ExperimentalStdlibApi::class) override fun getConstructors(): Collection<ClassConstructorDescriptor> = context.withAnalysisSession { ktSymbol.getDeclaredMemberScope().getConstructors().map { KtSymbolBasedConstructorDescriptor(it, this@KtSymbolBasedClassDescriptor) }.toList() } override fun getPackageFqNameIfTopLevel(): FqName = (ktSymbol.classIdIfNonLocal ?: error("should be top-level")).packageFqName override fun getSealedSubclasses(): Collection<ClassDescriptor> = implementationPostponed() override fun getValueClassRepresentation(): ValueClassRepresentation<SimpleType> = TODO("Not yet implemented") override fun getMemberScope(typeArguments: MutableList<out TypeProjection>): MemberScope = noImplementation() override fun getMemberScope(typeSubstitution: TypeSubstitution): MemberScope = noImplementation() override fun getUnsubstitutedMemberScope(): MemberScope = noImplementation() override fun getUnsubstitutedInnerClassesScope(): MemberScope = noImplementation() override fun getStaticScope(): MemberScope = noImplementation() override fun isDefinitelyNotSamInterface(): Boolean = noImplementation() override fun getDefaultFunctionTypeForSamInterface(): SimpleType = noImplementation() } class KtSymbolBasedTypeParameterDescriptor( override val ktSymbol: KtTypeParameterSymbol, context: FE10BindingContext ) : KtSymbolBasedDeclarationDescriptor(context), KtSymbolBasedNamed, TypeParameterDescriptor { override fun isReified(): Boolean = ktSymbol.isReified override fun getVariance(): Variance = ktSymbol.variance override fun getTypeConstructor(): TypeConstructor = KtSymbolBasedTypeParameterTypeConstructor(this) override fun getDefaultType(): SimpleType = KotlinTypeFactory.simpleTypeWithNonTrivialMemberScope( TypeAttributes.Empty, typeConstructor, emptyList(), false, MemberScopeForKtSymbolBasedDescriptors { "ktSymbol = $ktSymbol" } ) override fun getUpperBounds(): List<KotlinType> = ktSymbol.upperBounds.map { it.toKotlinType(context) } override fun getOriginal(): TypeParameterDescriptor = this override fun getContainingDeclaration(): DeclarationDescriptor = context.containerDeclarationImplementationPostponed() override fun getPackageFqNameIfTopLevel(): FqName = error("Should be called") // there is no such thing in FIR, and it seems like it isn't really needed for IDE and could be bypassed on client site override fun getIndex(): Int = implementationPostponed() override fun isCapturedFromOuterDeclaration(): Boolean = noImplementation() override fun getStorageManager(): StorageManager = noImplementation() } abstract class KtSymbolBasedFunctionLikeDescriptor(context: FE10BindingContext) : KtSymbolBasedDeclarationDescriptor(context), FunctionDescriptor { abstract override val ktSymbol: KtFunctionLikeSymbol override fun getReturnType(): KotlinType = ktSymbol.returnType.toKotlinType(context) override fun getValueParameters(): List<ValueParameterDescriptor> = ktSymbol.valueParameters.mapIndexed { index, it -> KtSymbolBasedValueParameterDescriptor(it, context,this, index) } override fun hasStableParameterNames(): Boolean = implementationPostponed() override fun hasSynthesizedParameterNames(): Boolean = implementationPostponed() override fun getKind(): CallableMemberDescriptor.Kind = implementationPostponed() override fun <V : Any?> getUserData(key: CallableDescriptor.UserDataKey<V>?): V? = null override fun getOriginal(): FunctionDescriptor = this override fun isHiddenForResolutionEverywhereBesideSupercalls(): Boolean = implementationPostponed() override fun getInitialSignatureDescriptor(): FunctionDescriptor? = noImplementation() override fun isHiddenToOvercomeSignatureClash(): Boolean = noImplementation() override fun setOverriddenDescriptors(overriddenDescriptors: MutableCollection<out CallableMemberDescriptor>) = noImplementation() override fun newCopyBuilder(): FunctionDescriptor.CopyBuilder<out FunctionDescriptor> = noImplementation() override fun copy( newOwner: DeclarationDescriptor?, modality: Modality?, visibility: DescriptorVisibility?, kind: CallableMemberDescriptor.Kind?, copyOverrides: Boolean ): FunctionDescriptor = noImplementation() } class KtSymbolBasedFunctionDescriptor(override val ktSymbol: KtFunctionSymbol, context: FE10BindingContext) : KtSymbolBasedFunctionLikeDescriptor(context), SimpleFunctionDescriptor, KtSymbolBasedNamed { override fun getExtensionReceiverParameter(): ReceiverParameterDescriptor? = getExtensionReceiverParameter(ktSymbol) override fun getDispatchReceiverParameter(): ReceiverParameterDescriptor? = getDispatchReceiverParameter(ktSymbol) override fun getContextReceiverParameters(): List<ReceiverParameterDescriptor> = implementationPlanned() override fun getPackageFqNameIfTopLevel(): FqName = (ktSymbol.callableIdIfNonLocal ?: error("should be top-level")).packageName override fun isSuspend(): Boolean = ktSymbol.isSuspend override fun isOperator(): Boolean = ktSymbol.isOperator override fun isExternal(): Boolean = ktSymbol.isExternal override fun isInline(): Boolean = ktSymbol.isInline override fun isInfix(): Boolean = implementationPostponed() override fun isTailrec(): Boolean = implementationPostponed() override fun isExpect(): Boolean = context.incorrectImplementation { false } override fun isActual(): Boolean = context.incorrectImplementation { false } override fun getVisibility(): DescriptorVisibility = ktSymbol.visibility.toDescriptorVisibility() override fun getModality(): Modality = ktSymbol.modality override fun getTypeParameters(): List<TypeParameterDescriptor> = getTypeParameters(ktSymbol) override fun getOverriddenDescriptors(): Collection<FunctionDescriptor> { val overriddenKtSymbols = context.withAnalysisSession { ktSymbol.getAllOverriddenSymbols() } return overriddenKtSymbols.map { KtSymbolBasedFunctionDescriptor(it as KtFunctionSymbol, context) } } override fun copy( newOwner: DeclarationDescriptor?, modality: Modality?, visibility: DescriptorVisibility?, kind: CallableMemberDescriptor.Kind?, copyOverrides: Boolean ): SimpleFunctionDescriptor = context.noImplementation() override fun getOriginal(): SimpleFunctionDescriptor = context.incorrectImplementation { this } override fun newCopyBuilder(): FunctionDescriptor.CopyBuilder<out SimpleFunctionDescriptor> = context.noImplementation() } class KtSymbolBasedConstructorDescriptor( override val ktSymbol: KtConstructorSymbol, private val ktSBClassDescriptor: KtSymbolBasedClassDescriptor ) : KtSymbolBasedFunctionLikeDescriptor(ktSBClassDescriptor.context), ClassConstructorDescriptor { override fun getName(): Name = Name.special("<init>") override fun getExtensionReceiverParameter(): ReceiverParameterDescriptor? = null override fun getDispatchReceiverParameter(): ReceiverParameterDescriptor? = getDispatchReceiverParameter(ktSymbol) override fun getContextReceiverParameters(): List<ReceiverParameterDescriptor> = ktSBClassDescriptor.contextReceivers override fun getConstructedClass(): ClassDescriptor = ktSBClassDescriptor override fun getContainingDeclaration(): ClassDescriptor = ktSBClassDescriptor override fun getPackageFqNameIfTopLevel(): FqName = error("should not be called") override fun isPrimary(): Boolean = ktSymbol.isPrimary override fun getReturnType(): KotlinType = ktSBClassDescriptor.defaultType override fun isSuspend(): Boolean = false override fun isOperator(): Boolean = false override fun isExternal(): Boolean = false override fun isInline(): Boolean = false override fun isInfix(): Boolean = false override fun isTailrec(): Boolean = false override fun isExpect(): Boolean = implementationPostponed() override fun isActual(): Boolean = implementationPostponed() override fun getVisibility(): DescriptorVisibility = ktSymbol.visibility.toDescriptorVisibility() override fun getModality(): Modality = Modality.FINAL override fun getTypeParameters(): List<TypeParameterDescriptor> = getTypeParameters(ktSymbol) override fun getOriginal(): ClassConstructorDescriptor = this override fun getOverriddenDescriptors(): Collection<FunctionDescriptor> = emptyList() override fun copy( newOwner: DeclarationDescriptor, modality: Modality, visibility: DescriptorVisibility, kind: CallableMemberDescriptor.Kind, copyOverrides: Boolean ): ClassConstructorDescriptor = noImplementation() } class KtSymbolBasedAnonymousFunctionDescriptor( override val ktSymbol: KtAnonymousFunctionSymbol, context: FE10BindingContext ) : KtSymbolBasedFunctionLikeDescriptor(context), SimpleFunctionDescriptor { override fun getName(): Name = SpecialNames.ANONYMOUS override fun getExtensionReceiverParameter(): ReceiverParameterDescriptor? = getExtensionReceiverParameter(ktSymbol) override fun getDispatchReceiverParameter(): ReceiverParameterDescriptor? = null override fun getContextReceiverParameters(): List<ReceiverParameterDescriptor> = implementationPlanned() override fun getPackageFqNameIfTopLevel(): FqName = error("Impossible to be a top-level declaration") override fun isOperator(): Boolean = false override fun isExternal(): Boolean = false override fun isInline(): Boolean = false override fun isInfix(): Boolean = false override fun isTailrec(): Boolean = false override fun isExpect(): Boolean = false override fun isActual(): Boolean = false override fun getVisibility(): DescriptorVisibility = DescriptorVisibilities.LOCAL override fun getModality(): Modality = Modality.FINAL override fun getTypeParameters(): List<TypeParameterDescriptor> = emptyList() // it doesn't seems like isSuspend are used in FIR for anonymous functions, but it used in FIR2IR so if we really need that // we could implement that later override fun isSuspend(): Boolean = implementationPostponed() override fun getOverriddenDescriptors(): Collection<FunctionDescriptor> = emptyList() override fun copy( newOwner: DeclarationDescriptor?, modality: Modality?, visibility: DescriptorVisibility?, kind: CallableMemberDescriptor.Kind?, copyOverrides: Boolean ): SimpleFunctionDescriptor = noImplementation() override fun getOriginal(): SimpleFunctionDescriptor = this override fun newCopyBuilder(): FunctionDescriptor.CopyBuilder<out SimpleFunctionDescriptor> = noImplementation() } private fun KtSymbolBasedDeclarationDescriptor.getDispatchReceiverParameter(ktSymbol: KtCallableSymbol): ReceiverParameterDescriptor? { val ktDispatchTypeAndAnnotations = context.withAnalysisSession { ktSymbol.getDispatchReceiverType() } ?: return null return KtSymbolStubDispatchReceiverParameterDescriptor(ktDispatchTypeAndAnnotations, context) } private fun <T> T.getExtensionReceiverParameter( ktSymbol: KtCallableSymbol, ): ReceiverParameterDescriptor? where T : KtSymbolBasedDeclarationDescriptor, T : CallableDescriptor { val receiverType = ktSymbol.receiverType ?: return null val receiverValue = ExtensionReceiver(this, receiverType.toKotlinType(context), null) return ReceiverParameterDescriptorImpl(this, receiverValue, receiverType.getDescriptorsAnnotations(context)) } private fun KtSymbolBasedDeclarationDescriptor.getTypeParameters(ktSymbol: KtSymbolWithTypeParameters) = ktSymbol.typeParameters.map { KtSymbolBasedTypeParameterDescriptor(it, context) } private class KtSymbolBasedReceiverValue(val ktType: KtType, val context: FE10BindingContext) : ReceiverValue { override fun getType(): KotlinType = ktType.toKotlinType(context) override fun replaceType(newType: KotlinType): ReceiverValue = context.noImplementation("Should be called from IDE") override fun getOriginal(): ReceiverValue = this } // Don't think that annotation is important here, because containingDeclaration used way more then annotation and they are not supported here private class KtSymbolStubDispatchReceiverParameterDescriptor( val receiverType: KtType, val context: FE10BindingContext ) : AbstractReceiverParameterDescriptor(Annotations.EMPTY) { override fun getContainingDeclaration(): DeclarationDescriptor = context.containerDeclarationImplementationPostponed() override fun getValue(): ReceiverValue = KtSymbolBasedReceiverValue(receiverType, context) override fun copy(newOwner: DeclarationDescriptor): ReceiverParameterDescriptor = context.noImplementation("Copy should be called from IDE code") } class KtSymbolBasedValueParameterDescriptor( override val ktSymbol: KtValueParameterSymbol, context: FE10BindingContext, val containingDeclaration: KtSymbolBasedFunctionLikeDescriptor, index: Int = -1, ) : KtSymbolBasedDeclarationDescriptor(context), KtSymbolBasedNamed, ValueParameterDescriptor { override val index: Int init { if (index != -1) { this.index = index } else { val containerSymbol = containingDeclaration.ktSymbol this.index = containerSymbol.valueParameters.indexOfFirst { it === ktSymbol } check(this.index != -1) { "Parameter not found in container symbol = $containerSymbol" } } } override fun getExtensionReceiverParameter(): ReceiverParameterDescriptor? = null override fun getDispatchReceiverParameter(): ReceiverParameterDescriptor? = null override fun getContextReceiverParameters(): List<ReceiverParameterDescriptor> = emptyList() override fun getTypeParameters(): List<TypeParameterDescriptor> = emptyList() override fun getReturnType(): KotlinType = ktSymbol.returnType.toKotlinType(context) override fun getValueParameters(): List<ValueParameterDescriptor> = emptyList() override fun hasStableParameterNames(): Boolean = false override fun hasSynthesizedParameterNames(): Boolean = false override fun <V : Any?> getUserData(key: CallableDescriptor.UserDataKey<V>?): V? = null override fun getVisibility(): DescriptorVisibility = DescriptorVisibilities.LOCAL override fun getType(): KotlinType = ktSymbol.returnType.toKotlinType(context) override fun getContainingDeclaration(): CallableDescriptor = containingDeclaration override fun getPackageFqNameIfTopLevel(): FqName = error("Couldn't be top-level") override fun declaresDefaultValue(): Boolean = ktSymbol.hasDefaultValue override val varargElementType: KotlinType? get() { if (!ktSymbol.isVararg) return null return context.builtIns.getArrayElementType(type) } override fun cleanCompileTimeInitializerCache() {} override fun getOriginal(): ValueParameterDescriptor = context.incorrectImplementation { this } override fun copy(newOwner: CallableDescriptor, newName: Name, newIndex: Int): ValueParameterDescriptor = context.noImplementation() override fun getOverriddenDescriptors(): Collection<ValueParameterDescriptor> { return containingDeclaration.overriddenDescriptors.map { valueParameters[index] } } override val isCrossinline: Boolean get() = implementationPostponed() override val isNoinline: Boolean get() = implementationPostponed() override fun isVar(): Boolean = false override fun getCompileTimeInitializer(): ConstantValue<*>? = null override fun isConst(): Boolean = false override fun equals(other: Any?): Boolean { if (other === this) return true if (other !is KtSymbolBasedValueParameterDescriptor) return false return index == other.index && containingDeclaration == other.containingDeclaration } override fun hashCode(): Int = containingDeclaration.hashCode() * 37 + index } class KtSymbolBasedPropertyDescriptor( override val ktSymbol: KtPropertySymbol, context: FE10BindingContext ) : KtSymbolBasedDeclarationDescriptor(context), KtSymbolBasedNamed, PropertyDescriptor { override fun getPackageFqNameIfTopLevel(): FqName = (ktSymbol.callableIdIfNonLocal ?: error("should be top-level")).packageName override fun getOriginal(): PropertyDescriptor = context.incorrectImplementation { this } override fun getVisibility(): DescriptorVisibility = ktSymbol.visibility.toDescriptorVisibility() override fun getExtensionReceiverParameter(): ReceiverParameterDescriptor? = getExtensionReceiverParameter(ktSymbol) override fun getDispatchReceiverParameter(): ReceiverParameterDescriptor? = getDispatchReceiverParameter(ktSymbol) override fun getContextReceiverParameters(): List<ReceiverParameterDescriptor> = implementationPlanned() override fun getTypeParameters(): List<TypeParameterDescriptor> = emptyList() override fun getReturnType(): KotlinType = ktSymbol.returnType.toKotlinType(context) override fun getValueParameters(): List<ValueParameterDescriptor> = emptyList() override fun hasStableParameterNames(): Boolean = false override fun hasSynthesizedParameterNames(): Boolean = false override fun getOverriddenDescriptors(): Collection<PropertyDescriptor> = implementationPostponed() override fun <V : Any?> getUserData(key: CallableDescriptor.UserDataKey<V>?): V? = null override fun getType(): KotlinType = ktSymbol.returnType.toKotlinType(context) override fun isVar(): Boolean = !ktSymbol.isVal override fun getCompileTimeInitializer(): ConstantValue<*>? { val constantInitializer = ktSymbol.initializer as? KtConstantInitializerValue ?: return null return constantInitializer.constant.toConstantValue() } override fun cleanCompileTimeInitializerCache() {} override fun isConst(): Boolean = ktSymbol.initializer != null override fun isLateInit(): Boolean = implementationPostponed() override fun getModality(): Modality = implementationPlanned() override fun isExpect(): Boolean = implementationPostponed() override fun isActual(): Boolean = implementationPostponed() override fun isExternal(): Boolean = implementationPlanned() override fun getInType(): KotlinType? = implementationPostponed() override fun setOverriddenDescriptors(overriddenDescriptors: MutableCollection<out CallableMemberDescriptor>) = noImplementation() override fun getKind(): CallableMemberDescriptor.Kind = implementationPlanned() override fun copy( newOwner: DeclarationDescriptor?, modality: Modality?, visibility: DescriptorVisibility?, kind: CallableMemberDescriptor.Kind?, copyOverrides: Boolean ): CallableMemberDescriptor = noImplementation() override fun newCopyBuilder(): CallableMemberDescriptor.CopyBuilder<out PropertyDescriptor> = noImplementation() override fun isSetterProjectedOut(): Boolean = implementationPostponed() override fun getAccessors(): List<PropertyAccessorDescriptor> = listOfNotNull(getter, setter) override fun getBackingField(): FieldDescriptor? = implementationPostponed() override fun getDelegateField(): FieldDescriptor? = implementationPostponed() override val isDelegated: Boolean get() = implementationPostponed() override val getter: PropertyGetterDescriptor? get() = ktSymbol.getter?.let { KtSymbolBasedPropertyGetterDescriptor(it, this) } override val setter: PropertySetterDescriptor? get() = ktSymbol.setter?.let { KtSymbolBasedPropertySetterDescriptor(it, this) } } abstract class KtSymbolBasedVariableAccessorDescriptor( val propertyDescriptor: KtSymbolBasedPropertyDescriptor ) : KtSymbolBasedDeclarationDescriptor(propertyDescriptor.context), VariableAccessorDescriptor { override abstract val ktSymbol: KtPropertyAccessorSymbol override fun getPackageFqNameIfTopLevel(): FqName = error("should be called") override fun getContainingDeclaration(): DeclarationDescriptor = propertyDescriptor override val correspondingVariable: VariableDescriptorWithAccessors get() = propertyDescriptor override fun getExtensionReceiverParameter(): ReceiverParameterDescriptor? = propertyDescriptor.extensionReceiverParameter override fun getDispatchReceiverParameter(): ReceiverParameterDescriptor? = propertyDescriptor.dispatchReceiverParameter override fun getContextReceiverParameters(): List<ReceiverParameterDescriptor> = propertyDescriptor.contextReceiverParameters override fun getTypeParameters(): List<TypeParameterDescriptor> = emptyList() override fun getValueParameters(): List<ValueParameterDescriptor> = emptyList() override fun hasStableParameterNames(): Boolean = false override fun hasSynthesizedParameterNames(): Boolean = false override fun <V : Any?> getUserData(key: CallableDescriptor.UserDataKey<V>?): V? = null override fun setOverriddenDescriptors(overriddenDescriptors: MutableCollection<out CallableMemberDescriptor>) = noImplementation() override fun getKind(): CallableMemberDescriptor.Kind = propertyDescriptor.kind override fun getVisibility(): DescriptorVisibility = propertyDescriptor.visibility override fun getInitialSignatureDescriptor(): FunctionDescriptor? = noImplementation() override fun isHiddenToOvercomeSignatureClash(): Boolean = false override fun isOperator(): Boolean = false override fun isInfix(): Boolean = false override fun isInline(): Boolean = ktSymbol.isInline override fun isTailrec(): Boolean = false override fun isHiddenForResolutionEverywhereBesideSupercalls(): Boolean = implementationPostponed() override fun isSuspend(): Boolean = false override fun newCopyBuilder(): FunctionDescriptor.CopyBuilder<out FunctionDescriptor> = noImplementation() override fun getModality(): Modality = implementationPlanned() override fun isExpect(): Boolean = implementationPostponed() override fun isActual(): Boolean = implementationPostponed() override fun isExternal(): Boolean = implementationPostponed() } class KtSymbolBasedPropertyGetterDescriptor( override val ktSymbol: KtPropertyGetterSymbol, propertyDescriptor: KtSymbolBasedPropertyDescriptor ) : KtSymbolBasedVariableAccessorDescriptor(propertyDescriptor), PropertyGetterDescriptor { override fun getReturnType(): KotlinType = propertyDescriptor.returnType override fun getName(): Name = Name.special("<get-${propertyDescriptor.name}>") override fun isDefault(): Boolean = ktSymbol.isDefault override fun getCorrespondingProperty(): PropertyDescriptor = propertyDescriptor override fun copy( newOwner: DeclarationDescriptor?, modality: Modality?, visibility: DescriptorVisibility?, kind: CallableMemberDescriptor.Kind?, copyOverrides: Boolean ): PropertyAccessorDescriptor = noImplementation() override fun getOriginal(): PropertyGetterDescriptor = context.incorrectImplementation { this } override fun getOverriddenDescriptors(): Collection<PropertyGetterDescriptor> = implementationPostponed() } class KtSymbolBasedPropertySetterDescriptor( override val ktSymbol: KtPropertySetterSymbol, propertyDescriptor: KtSymbolBasedPropertyDescriptor ) : KtSymbolBasedVariableAccessorDescriptor(propertyDescriptor), PropertySetterDescriptor { override fun getReturnType(): KotlinType = propertyDescriptor.returnType override fun getName(): Name = Name.special("<set-${propertyDescriptor.name}>") override fun isDefault(): Boolean = ktSymbol.isDefault override fun getCorrespondingProperty(): PropertyDescriptor = propertyDescriptor override fun copy( newOwner: DeclarationDescriptor?, modality: Modality?, visibility: DescriptorVisibility?, kind: CallableMemberDescriptor.Kind?, copyOverrides: Boolean ): PropertyAccessorDescriptor = noImplementation() override fun getOriginal(): PropertySetterDescriptor = context.incorrectImplementation { this } override fun getOverriddenDescriptors(): Collection<PropertySetterDescriptor> = implementationPostponed() } class KtSymbolBasedPackageFragmentDescriptor( override val fqName: FqName, val context: FE10BindingContext ) : PackageFragmentDescriptor { override fun getName(): Name = fqName.shortName() override fun getOriginal(): DeclarationDescriptorWithSource = this override fun getSource(): SourceElement = SourceElement.NO_SOURCE override val annotations: Annotations get() = Annotations.EMPTY override fun getContainingDeclaration(): ModuleDescriptor = context.moduleDescriptor override fun getMemberScope(): MemberScope = context.noImplementation() override fun <R : Any?, D : Any?> accept(visitor: DeclarationDescriptorVisitor<R, D>?, data: D): R = context.noImplementation("IDE shouldn't use visitor on descriptors") override fun acceptVoid(visitor: DeclarationDescriptorVisitor<Void, Void>?) = context.noImplementation("IDE shouldn't use visitor on descriptors") }
apache-2.0
a76b584e5cdea0f5d4c1daed24ba5574
46.843871
158
0.764799
6.260172
false
false
false
false
jwren/intellij-community
plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/modules/IdeJavaModuleResolver.kt
4
4049
// 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.modules import com.intellij.codeInsight.daemon.impl.analysis.JavaModuleGraphUtil import com.intellij.openapi.project.Project import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.PsiJavaModule import com.intellij.psi.impl.light.LightJavaModule import org.jetbrains.kotlin.load.java.structure.JavaAnnotation import org.jetbrains.kotlin.load.java.structure.impl.JavaAnnotationImpl import org.jetbrains.kotlin.load.java.structure.impl.convert import org.jetbrains.kotlin.load.kotlin.VirtualFileFinder import org.jetbrains.kotlin.name.ClassId import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.resolve.jvm.modules.JavaModuleResolver import java.util.concurrent.ConcurrentHashMap class IdeJavaModuleResolver(private val project: Project) : JavaModuleResolver { private val virtualFileFinder by lazy { VirtualFileFinder.getInstance(project) } private val modulesAnnotationCache = ConcurrentHashMap<ClassId, List<JavaAnnotation>>() override fun getAnnotationsForModuleOwnerOfClass(classId: ClassId): List<JavaAnnotation>? { if (modulesAnnotationCache.containsKey(classId)) { return modulesAnnotationCache[classId] } val virtualFile = virtualFileFinder.findVirtualFileWithHeader(classId) ?: return null val moduleAnnotations = findJavaModule(virtualFile)?.annotations?.convert(::JavaAnnotationImpl) if (moduleAnnotations != null && moduleAnnotations.size < MODULE_ANNOTATIONS_CACHE_SIZE) { modulesAnnotationCache[classId] = moduleAnnotations } return moduleAnnotations } private fun findJavaModule(file: VirtualFile): PsiJavaModule? = JavaModuleGraphUtil.findDescriptorByFile(file, project) override fun checkAccessibility( fileFromOurModule: VirtualFile?, referencedFile: VirtualFile, referencedPackage: FqName? ): JavaModuleResolver.AccessError? { val ourModule = fileFromOurModule?.let(this::findJavaModule) val theirModule = findJavaModule(referencedFile) if (ourModule?.name == theirModule?.name) return null if (theirModule == null) { return JavaModuleResolver.AccessError.ModuleDoesNotReadUnnamedModule } if (ourModule != null && !JavaModuleGraphUtil.reads(ourModule, theirModule)) { return JavaModuleResolver.AccessError.ModuleDoesNotReadModule(theirModule.name) } // In the IDE, we allow unnamed module to access unexported package of the named module. The reason is that the compiler // will use classpath, not the module path, when compilation of this module is launched from the IDE (because the module has // no module-info). All of its dependencies will also land on the classpath, and everything is visible in the classpath, // even non-exported packages of artifacts which would otherwise be loaded as named modules, if they were on the module path. // So, no error will be reported from the compiler. Moreover, a run configuration of something from this unnamed module will also // use classpath, not the module path, and in the same way everything will work at runtime as well. if (ourModule != null) { val fqName = referencedPackage?.asString() ?: return null if (!exports(theirModule, fqName, ourModule)) { return JavaModuleResolver.AccessError.ModuleDoesNotExportPackage(theirModule.name) } } return null } // Returns whether or not [source] exports [packageName] to [target] private fun exports(source: PsiJavaModule, packageName: String, target: PsiJavaModule): Boolean = source is LightJavaModule || JavaModuleGraphUtil.exports(source, packageName, target) companion object { private const val MODULE_ANNOTATIONS_CACHE_SIZE = 10000 } }
apache-2.0
9434943968525a22ca21bafe4d7a41b3
49.6125
158
0.744875
4.849102
false
false
false
false
BijoySingh/Quick-Note-Android
base/src/main/java/com/maubis/scarlet/base/note/MarkdownExtensions.kt
1
3414
package com.maubis.scarlet.base.note import com.maubis.markdown.segmenter.MarkdownSegmentType import com.maubis.markdown.segmenter.TextSegmenter import com.maubis.scarlet.base.core.format.Format import com.maubis.scarlet.base.core.format.FormatType fun String.toInternalFormats(): List<Format> { return toInternalFormats( arrayOf( MarkdownSegmentType.HEADING_1, MarkdownSegmentType.HEADING_2, MarkdownSegmentType.HEADING_3, MarkdownSegmentType.BULLET_1, MarkdownSegmentType.BULLET_2, MarkdownSegmentType.BULLET_3, MarkdownSegmentType.CODE, MarkdownSegmentType.QUOTE, MarkdownSegmentType.CHECKLIST_UNCHECKED, MarkdownSegmentType.CHECKLIST_CHECKED, MarkdownSegmentType.SEPARATOR, MarkdownSegmentType.IMAGE)) } /** * Converts a string to the internal format types using the Markdown Segmentation Library. * It's possible to pass specific formats which will be preserved in the formats */ fun String.toInternalFormats(whitelistedSegments: Array<MarkdownSegmentType>): List<Format> { val extractedFormats = emptyList<Format>().toMutableList() val segments = TextSegmenter(this).get() var lastFormat: Format? = null segments.forEach { segment -> val isSegmentWhitelisted = whitelistedSegments.contains(segment.type()) val newFormat = when { !isSegmentWhitelisted -> null segment.type() == MarkdownSegmentType.HEADING_1 -> Format(FormatType.HEADING, segment.strip()) segment.type() == MarkdownSegmentType.HEADING_2 -> Format(FormatType.SUB_HEADING, segment.strip()) segment.type() == MarkdownSegmentType.HEADING_3 -> Format(FormatType.HEADING_3, segment.strip()) segment.type() == MarkdownSegmentType.BULLET_1 -> Format(FormatType.BULLET_1, segment.strip()) segment.type() == MarkdownSegmentType.BULLET_2 -> Format(FormatType.BULLET_2, segment.strip()) segment.type() == MarkdownSegmentType.BULLET_3 -> Format(FormatType.BULLET_3, segment.strip()) segment.type() == MarkdownSegmentType.CODE -> Format(FormatType.CODE, segment.strip()) segment.type() == MarkdownSegmentType.QUOTE -> Format(FormatType.QUOTE, segment.strip()) segment.type() == MarkdownSegmentType.CHECKLIST_UNCHECKED -> Format(FormatType.CHECKLIST_UNCHECKED, segment.strip()) segment.type() == MarkdownSegmentType.CHECKLIST_CHECKED -> Format(FormatType.CHECKLIST_CHECKED, segment.strip()) segment.type() == MarkdownSegmentType.SEPARATOR -> Format(FormatType.SEPARATOR) segment.type() == MarkdownSegmentType.IMAGE -> Format(FormatType.IMAGE, segment.strip().trim()) else -> null } val tempLastFormat = lastFormat when { tempLastFormat !== null && newFormat !== null -> { extractedFormats.add(tempLastFormat) extractedFormats.add(newFormat) lastFormat = null } tempLastFormat === null && newFormat !== null -> { extractedFormats.add(newFormat) } tempLastFormat !== null && newFormat === null -> { tempLastFormat.text += "\n" tempLastFormat.text += segment.text() lastFormat = tempLastFormat } tempLastFormat == null && newFormat === null -> { lastFormat = Format(FormatType.TEXT, segment.text()) } } } val tempLastFormat = lastFormat if (tempLastFormat !== null) { extractedFormats.add(tempLastFormat) } return extractedFormats }
gpl-3.0
8093842b767c710602cd7e120539fc83
42.227848
122
0.710603
4.251557
false
false
false
false